Dependency Injection in Composition Root: Pros and Cons

asp.net-mvcccompositiondependency-injection

I am using Dependency Injection for a .NET MVC web application in which I have three basic layers:

1) Web App
2) Service Layer
3) Data Layer

I inject the data layer into the service layer and the service layer into a controller in my web app which is all fine but I am confused over where the registering of these classes takes place.

After researching I've been told that the composition root is within the web application specifically in the Global.asax file which I have in my project, but this means that now I have a reference to the Data Layer within the web application in order to be able to register it. This seems to go against exactly what DI is for to me as I don't want my web app to know or care about the data layer only the service layer should have a reference?

Best Answer

Does Having DI Happen in the Composition Root go against the whole point of Dependency Injection?

No. You should create the object graph in the Composition Root.

I think that I understand the reason of your confusion. And I think that it is related to ASP.NET projects. To explain this, let me give first an example that does not involve ASP.NET.

Let's say we have a Console Application. We have created some class libraries that contain all the pieces of logic that our application need.

Let's say we created the following class libraries:

  1. ApplicationLibrary contains classes that are related to the application itself. It might contain some UI logic also.
  2. BusinessLogicLibrary contains classes related to business logic.
  3. DataAccessLibrary contains classes related to data access.

The ApplicationLibrary in this case does not have a reference to the DataAccessLibrary.

And then we compose these pieces together in the Console Application project. This project in this case does not contain anything except the composition root.

The thing with the ASP.NET projects is that by default we get a template in which the composition root and some Application/UI logic are in the same project.

What would be great is to have an ASP.NET web project that contains only the composition root (IControllerFactory implementation for example). And then move our Controllers and Views to another class library that does not have a reference to the DataAccessLayer since it is no longer the composition root.

You might even be able to do this with ASP.NET. I am not sure if there is an easy way though.

Related Topic