Where should I register my dependencies?

The Scenario:

You are developing a system, applying the S.O.L.I.D concepts and de inversion of control principle, you decide to use dependency injection and some DI Container.

The literature and the patterns tell us that the dependencies should be registered as close as possible to the entry point of an application, that is, usually the Main() method of an desktop application or the Startup() method of an ASPNET MVC application.

 

The problem:

If we follow this rule, our Composition Root (the place, close to the entry point of the application where dependencies should be registered) usually will be the ASPNET MVC project, because it is the entry point of an web application, to do so, this project will need to reference ALL the other projects of the application to register those assemblies in the DI container. It means that all our effort to split our application in tiers goes down the drain and your architecture would look like this:

The arrow point in the direction of the dependency, that is, View will depend on Business, Models, Data, etc.
The dependencies between Business, Models, Data, etc were omitted for didactic purposes.

This does NOT violate the Separation of Concerns principle the principle at class level but violate it at package level.
In this way, any developer who develops something in the View.dll assembly will be able to “mention / declare” classes from ANY other assembly. Congratulations, your project has become a mess, a SoC between components has been violated and changes in ANY Assembly of the project will impact the View. But how to solve this?

If you are interested in the “Component Coupling” topic, Robert Martin (Uncle Bob), in the 14 chapter of his book “Clean Architecture” discuss about component coupling, argues how this is harmful and points to solutions.

The Solution

In fact, there are two solutions you can adopt. And, to organize things i will split this in two posts, as follows:

Using the Plugin Architecture with DI Containers (less recommended)

Using the Composition Root (more recommended)

 

REFERENCES: