best layer for placing dependency injection related code in layered proeject

老子叫甜甜 提交于 2019-12-10 23:53:47

问题


I am planning to follow onion architecture for my new application.

the solution hierarchy is as follows

  • Domain - where all the interfaces for the services and repositories defined.
  • Infrastructure - this is the layer where all data access is placed. these classes typically implements interfaces defined in domain.
  • Web - this is my presentation part of the application. inside the same layer i have separate for folder for implementing the services defined in domain.

My plain is to use Dependency injection for dependency resolution. Initially i thought of placing DI related code in Infrastructure. But the problem is it leads to circular references while i map services, Because the actual service implementation is in my web project and the web project is referencing Infrastructure already. I can't move concrete services to another layer because it violates the principles of Onion Architecture ( transitive dependencies).

Any lead is appreciated.


回答1:


The answer depends on how you define 'DI related code'.

If you define DI as a set of principles and patterns that promote loose coupling and separation of concerns then these patterns (like Constructor Injection for example) should be applied at all layers of the application. Just like you would apply SOLID principles and other OO best practices.

If by DI you mean specific container and code that directly depends on this container then this code should only live in the entry point of you application. In your scenario, this is a Web layer. Or it can be a 'Main' procedure if this was a console app. This part of the application is referred to as Composition Root:

It’s easy to understand that each class should require its dependencies through its constructor, but this pushes the responsibility of composing the classes with their dependencies to a third party. Where should that be? It seems to me that most people are eager to compose as early as possible, but the correct answer is:

As close as possible to the application’s entry point.

This place is called the Composition Root of the application and defined like this:

A Composition Root is a (preferably) unique location in an application where modules are composed together.

This means that all the application code relies solely on Constructor Injection (or other injection patterns), but is never composed. Only at the entry point of the application is the entire object graph finally composed.



来源:https://stackoverflow.com/questions/12043091/best-layer-for-placing-dependency-injection-related-code-in-layered-proeject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!