Koen Barmentlo
Posted on March 25, 2024
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:
- https://docs.simpleinjector.org/en/latest/azurefunctionsintegration.html
- https://docs.autofac.org/en/latest/integration/azurefunctions.html
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;
}
}
If you prefer you can also create an extension method like this per feature instead of per class library.
Happy coding!
Posted on March 25, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 26, 2024