Created
July 30, 2023 16:43
-
-
Save skarllot/1284778e4c4a876e0ecaf1c837e06dc2 to your computer and use it in GitHub Desktop.
Register self with interfaces dependency injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.DependencyInjection.Extensions; | |
public static class ServiceCollectionExtensions | |
{ | |
public static IServiceCollection AddSelfWithInterfacesSingleton<TService>(this IServiceCollection services) | |
where TService : class | |
{ | |
services.AddSingleton<TService>(); | |
services.TryAdd( | |
typeof(TService) | |
.GetInterfaces() | |
.Select(static t => ServiceDescriptor.Singleton(t, static sp => sp.GetRequiredService<TService>()))); | |
return services; | |
} | |
public static IServiceCollection AddSelfWithInterfacesScoped<TService>(this IServiceCollection services) | |
where TService : class | |
{ | |
services.AddScoped<TService>(); | |
services.TryAdd( | |
typeof(TService) | |
.GetInterfaces() | |
.Select(static t => ServiceDescriptor.Scoped(t, static sp => sp.GetRequiredService<TService>()))); | |
return services; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment