Dependency injection in an n-tier application?

I have a three-tier .NET service application that follows standard approaches:

Frontend -> Object Model / Business Logic -> Data Access 

I am trying to learn about dependency injection along the way, and still found it wonderful (using Autofac). Each of the three levels needs to create an assortment of objects, sometimes with an additional configuration /, etc. It seems that the DI container should be the perfect solution to solve this problem, but I am having problems with where it should live in relation to the rest of the system.

I currently have a class in the interface that configures the DI container. This is basically a big piece of code saying container.Register<SomeType>() and so on.

The problem is that it configures the container for all three levels and, therefore, must have fairly invasive knowledge of the level of data access. The presence of code in my interface with such knowledge imposes alarming calls on me, since the point of dividing the application into levels is to avoid this particular situation.
This is also compounded by the fact that my level of data access is not just a SQL server, which is a dumb bucket of bits, but it is composed of many complex COM interactions and P / Invoke calls, so it has a big impact on DI configurations.

I thought about breaking it up - perhaps with one container per level or with the “Setup” class at each level that talks to the global DI container to register its own bits, but I'm not sure what will cause more problems. what decides ...

I would really appreciate it if anyone could share their experience using DI with layered applications.

Thanks, Orion.

+7
dependency-injection n-tier
source share
1 answer

It depends on whether you have three levels (physical separation) or all your logical levels are deployed together. If the external interface is separate from your BL and interacts via webservice or WCF, then the interface and backend must have their own containers, because they work in separate processes or separate machines. Containers will only register their own components and "next" level interfaces.

On the other hand, if all layers work in the same process, then you should have only one container. The container will be initialized and placed at the starting point of the application, for example global.asax for the web application.

The problem with the container node that knows many of the different parts of the system can be solved by not observing the classes one by one, and instead register all types in the assembly. Thus, you do not need strong links to all the assemblies in your solution in order to configure the container. An example of how this can be done with Castle Winsdor:

 Kernel.Register(AllTypes.Pick().FromAssemblyName("DataAccessLayer.dll")); Kernel.Register(AllTypes.Pick().FromAssemblyName("BusinessLogic.dll")); 
+2
source share

All Articles