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
public interface IArticleService { } public class ArticleService : IArticleService { }
The current process requires this new service to be registered in the container as below.
unityContainer.RegisterType<IArticleService, ArticleService>();
or if you were to use Ninject, this would look like
kernel.Bind<IArticleService>().To<ArticleService>();
New solution
Firstly, all service interfaces need to derive from a common interface i.e IService
public interface IService { } public interface IArticleService : IService { } public class ArticleService : IArticleService { }
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.
unityContainer.RegisterTypes( AllClasses.FromLoadedAssemblies() .Where(type => typeof(IService).IsAssignableFrom(type) && !type.IsAbstract && !type.IsInterface), WithMappings.FromMatchingInterface, WithName.Default, WithLifetime.PerResolve);
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.
kernel.Bind(x => { x.From(AppDomain.CurrentDomain.GetAssemblies()) .IncludingNonePublicTypes() .SelectAllClasses() .InheritedFrom<IService>() .BindDefaultInterface(); });
That’s it. So as long as your new services interface implements the common IService interface, the service will be registered automatically.