Pergunta

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 implement interfaces defined in the domain.
  • Web - this is my presentation part of the application. inside the same layer, I have a separate folder for implementing the services defined in the domain.

My plan 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.

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top