Automatically register/resolve dependencies using loaded assemblies

In my current projects, whenever a new service is added, I need to manually register it in the container if using Unity or bind it in the kernel if using Ninject. This is working alright for the team so far but there is a way to automate this process. The idea is to look into the loaded assemblies and look for all the classes that implement the same base service interface to register these new services on application startup.

Current process

Let’s say we have an ArticleService.cs which implements an IArticleService.cs

The current process requires this new service to be registered in the container as below.

or if you were to use Ninject, this would look like

New solution

Firstly, all service interfaces need to derive from a common interface i.e IService

As mentioned above, we’ll then scan the loaded assemblies for all classes that implement this IService interface and register/bind them in application startup.

The last parameter WithLifetime.PerResolve is used so that instances are reused. See here for other options.

With Ninject, to be able to do something similar, you’ll need to install an additional Nuget package called Ninject.Extensions.Conventions. Once installed, you will be able to bind services to the kernel by scanning the loaded assemblies.

That’s it. So as long as your new services interface implements the common IService interface, the service will be registered automatically.

Like this post?

Leave a Reply

Your email address will not be published. Required fields are marked *