Created
February 25, 2025 22:20
-
-
Save skarllot/de72261df8e562881086c4779660c3fe to your computer and use it in GitHub Desktop.
The equivalent of AsImplementedInterfaces+InstancePerLifetimeScope from AutoFac on Microsoft DependencyInjection
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 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