Skip to content

Instantly share code, notes, and snippets.

@skarllot
Created July 30, 2023 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skarllot/1284778e4c4a876e0ecaf1c837e06dc2 to your computer and use it in GitHub Desktop.
Save skarllot/1284778e4c4a876e0ecaf1c837e06dc2 to your computer and use it in GitHub Desktop.
Register self with interfaces dependency injection
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