Created
October 5, 2020 09:16
-
-
Save NDiiong/145d6e6520f8f18f41e2111fab556dba to your computer and use it in GitHub Desktop.
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
public static class CollectionServiceExtension | |
{ | |
public static IServiceCollection Registers<TService>(this IServiceCollection services, ServiceLifetime lifetime, params Assembly[] assemblies) | |
where TService : class | |
{ | |
return services.Registers(lifetime, assemblies, typeof(TService)); | |
} | |
public static IServiceCollection Registers(this IServiceCollection services, ServiceLifetime lifetime, Assembly assemblies, params Type[] interfaceTypes) | |
{ | |
return services.Registers(lifetime, new[] { assemblies }, interfaceTypes); | |
} | |
/// <summary> | |
/// | |
/// </summary> | |
/// <param name="services"></param> | |
/// <param name="pattern">Example: "*.Repository.*.dll"</param> | |
/// <param name="interfaceTypes"></param> | |
/// <param name="lifetime"></param> | |
/// <returns></returns> | |
public static IServiceCollection Registers(this IServiceCollection services, ServiceLifetime lifetime, string pattern, params Type[] interfaceTypes) | |
{ | |
var assemblies = new List<Assembly>(); | |
foreach (string assemblyPath in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, pattern, SearchOption.TopDirectoryOnly)) | |
{ | |
var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath); | |
assemblies.Add(assembly); | |
} | |
return services.Registers(lifetime, assemblies.ToArray(), interfaceTypes); | |
} | |
public static IServiceCollection Registers(this IServiceCollection services, ServiceLifetime lifetime, Assembly[] assemblies, params Type[] interfaceTypes) | |
{ | |
foreach (var type in assemblies.SelectMany(x => x.GetTypes().Where(t => t.IsClass && !t.IsAbstract))) | |
{ | |
foreach (var i in type.GetInterfaces()) | |
{ | |
foreach (var interfaceType in interfaceTypes) | |
{ | |
// Check for generic | |
if (i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType) | |
{ | |
var genericInterfaceType = interfaceType.MakeGenericType(i.GetGenericArguments()); | |
if (!services.Any(f => f.ServiceType == genericInterfaceType && f.ImplementationType == type)) | |
services.Add(new ServiceDescriptor(genericInterfaceType, type, lifetime)); | |
} | |
// Check for non-generic | |
else if (!i.IsGenericType && i == interfaceType) | |
{ | |
if (!services.Any(f => f.ServiceType == interfaceType && f.ImplementationType == type)) | |
{ | |
services.Add(new ServiceDescriptor(interfaceType, type, lifetime)); | |
} | |
} | |
} | |
} | |
} | |
return services; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment