Say, that I have the following project structure:
Application <-> BusinessLogic <-> DataAccessLayer
I've prepared all types to use poor-man's-dependency-injection and now I want to introduce the real one using Unity. But I'm struggling on where to put the dependency container and its configuration (i suppose I'll configure it from code).
For now, the only assembly, which uses the container to actually instantiate classes will be the Application. So I have the following dependency diagram:
I have circular reference here, so it seems legit to put DI inside Application. But then I'd have to reference DataAccessLayer and that's a dependency I don't want to create. How should I resolve this problem?
In software engineering, dependency injection is a design pattern in which an object or function receives other objects or functions that it depends on. A form of inversion of control, dependency injection aims to separate the concerns of constructing objects and using them, leading to loosely coupled programs.
The goal of the dependency injection technique is to remove this dependency by separating the usage from the creation of the object. This reduces the amount of required boilerplate code and improves flexibility.
Dependency injection moves the dependencies to the interface of components. This makes it easier to see what dependencies a component has, making the code more readable. You don't have to look through all the code to see what dependencies you need to satisfy for a given component. They are all visible in the interface.
If you want to use a DI container, then you should only use it in the Application itself, not in your other class libraries (e.g. BusinessLogic and DataAccessLayer). The place in the Application where you compose your object graph is called the Composition Root.
Quoting for that article:
Only applications should have Composition Roots. Libraries and frameworks shouldn't.
Since you have already prepared your classes to enable poor man DI (now called Pure DI), you should be fine. DI is now enabled in your libraries (Please note that DI and DI containers are different things).
Your application now can wire everything together from all the class libraries, even if that means that your application project will need to reference all the other class libraries.
In my opinion, you would be better off without a DI container (even in the application layer), see this article for a reason why.
That way the relatively upper layer is shielded from the lower layers and everything is properly registered. To the A layer it is an implementation detail that the DL even exists. It only knows about the BL layer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With