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).
- DataAccessLayer needs to register Context (EF)
- BusinessLogic needs to register data repositories (which use context)
- Application needs to register services (which use repositories)
For now, the only assembly, which uses the container to actually instantiate classes will be the Application. So I have the following dependency diagram:
- DI uses DataAccessLayer
- DI uses BusinessLogic
- DI uses Application
- Application uses DI
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?
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:
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.