Plugin Architecture with DI Containers

Before, read my other post explaining why this is so important.

This architecture is about to make make each assembly register their own dependencies. The idea is to develop a class that receives the DI Container by parameter and register the dependencies in that container. This class is called by reflection from somewhere next to the starting point of your application, most DI Container nowadays have this feature:

Here is an example:

Then, next to the entry point of your application, tell to your DI Library (in our case, the SimpleInjector): Hey, inspect ALL of my DLL’s for a class who implements IPackage, if theres any, calls the RegisterServices() Method on it!

Done! All the dependencies of all your DLLs will be registered in the container, now you can Resolve any dependency you need normally, like this:

NOTE: When your view is an ASP.NET MVC Application (.Net Framework), you don’t explicitly call a method from the container to resolve your dependencies, in other hand, you should “teach” to asp.net mvc that the “resolver” of dependencies is now a SimpleInjector responsibility, the code to make it is the follow:

Here is an exemple on how to integrate the SimpleInjector with the AspNet MVC “full” framework.

NOTE2: When your view is an ASP.NET MVC Application (.Net Core), there is a lot controversy between the Microsoft engineers and the Dependency Injection libraries developers on how the .Net Core should work with external DI Container. Your can read more about it on this link.

Anyway, here is an example on how to integrate the SimpleInjector with the AspNet MVC Core framework.

Pros:

  • Your assemblies will work like a plugin, you just need to compile it and drop it in the application production folder and all the dependencies will be registered when the application starts.
  • The Dependency Graph becomes flatter and simpler.

Cons:

  • The dependency registration will be “spread” by the code base.
  • Each new assembly should follow the “plugin concept”.
  • All the assemblies should reference the DI Container assembly of choice to be able to register the dependencies (not a big deal).
  • Uses reflection.

Check my Github for a complete project that shows all the techniques explained above.

 

REFERENCES: