DEV Community

Koen Barmentlo
Koen Barmentlo

Posted on

4

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!

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more