DEV Community

Koen Barmentlo
Koen Barmentlo

Posted on

Modular Dependency Injection in .NET

When I was building application with .NET Framework I always used libraries like Autofac and SimpleInjector for dependency injection. I really liked to create modules (Packages in SimpleInjector) to achieve higher cohesion and lower coupling in my class libraries. I made a module for every class library in which all dependencies inside of that class library were registered. Why should my web application (for example) know if MyBeautifulService in MyBeautifulClassLibrary should be transient or singleton?

.NET Core 1.0 has built-in dependency injection support but it still lacks modules in later .NET versions (or that's what I thought). While it is possible to use Autofac and SimpleInjector in .NET Core I ran into issues and difficulties pretty quickly when I was building some Azure Functions:

I build my own Module feature with the Microsoft dependency injection which was pretty easy to do. But the way I was thinking was much to difficult. Why would I not do it in the same way Microsoft is doing it? So now I do it like this:

public static class MyBeautifulClassLibraryExtensions
{
    public static IServiceCollection UseMyBeautifulClassLibrary(this IServiceCollection services)
    {
        services.AddTransient<MyBeautifulService>();
        return services;
    }
}
Enter fullscreen mode Exit fullscreen mode

If you prefer you can also create an extension method like this per feature instead of per class library.

Happy coding!

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

Hi Koen Barmentlo,
Your tips are very useful
Thanks for sharing