Skip to content

Instantly share code, notes, and snippets.

@skarllot
Created February 25, 2025 22:20
Show Gist options
  • Save skarllot/de72261df8e562881086c4779660c3fe to your computer and use it in GitHub Desktop.
Save skarllot/de72261df8e562881086c4779660c3fe to your computer and use it in GitHub Desktop.
The equivalent of AsImplementedInterfaces+InstancePerLifetimeScope from AutoFac on Microsoft DependencyInjection
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Example;
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddImplementedInterfacesAsScoped(
this IServiceCollection services,
Assembly assembly,
string interfaceNamespacePrefix
)
{
var interfaceFilter = (Type t) => t.Namespace?.StartsWith(interfaceNamespacePrefix) == true;
services.Add(
assembly
.GetTypes()
.Where(t =>
t is { IsClass: true, IsAbstract: false, IsNested: false } && t.GetInterfaces().Any(interfaceFilter)
)
.SelectMany(t => t.GetInterfaces().Where(interfaceFilter).Select(i => (t, i)))
.Select(x =>
ServiceDescriptor.Scoped(x.t.IsGenericTypeDefinition ? x.i.GetGenericTypeDefinition() : x.i, x.t)
)
.Where(x =>
x.ImplementationType!.GetGenericArguments().Length <= x.ServiceType.GetGenericArguments().Length
)
);
return services;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment