In my NuGet package, I want to add a method that receives the ServiceLifetime lifetime
parameter and adds a service to the DI container using it.
I have implemented it with the code
public static void AddProvider(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Singleton)
{
var descriptor = new ServiceDescriptor(
typeof(IEnvironmentVariableProvider),
typeof(EnvironmentVariableProvider),
lifetime);
services.Add(descriptor);
}
Is there a more concise method?
CodePudding user response:
There isn't really a (much) more concise way to do what you want. What you have is fine.
If you look at the source for ASP.NET's ServiceCollectionExtensions
, it has a private method that looks a lot like yours (of course it takes two type parameters, where you've "hardcoded" them to your specific types.
If you find yourself making more Add
type methods and don't mind rolling another extension method, you could create an extension method like
public static class MyServiceCollectionExtensions
{
public static void AddDynamic<TInterface, TClass>(
this IServiceCollection services,
ServiceLifetime lifetime = ServiceLifetime.Singleton
)
where TClass : class, TInterface
where TInterface : class
{
services.Add(new ServiceDescriptor(typeof(TInterface), typeof(TClass), lifetime);
}
}
and then your call would be a little bit more concise.
public static void AddProvider(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Singleton)
{
services.AddDynamic<IEnvironmentVariableProvider, EnvironmentVariableProvider>(lifetime);
}