Last active
June 1, 2017 20:24
-
-
Save thiagomajesk/204ca7e602c3a1f1d5cc6f7b4ab42aa9 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 IServiceCollectionExtensions | |
{ | |
public static IServiceCollection ConnectImplementations<TService>(this IServiceCollection services, Assembly assembly)where TService : class | |
{ | |
return services.ConnectImplementations(typeof (TService), assembly); | |
} | |
public static IServiceCollection ConnectImplementations(this IServiceCollection services, Type serviceType, Assembly assembly) | |
{ | |
if (!serviceType.IsInterface) throw new ArgumentException($"{nameof(serviceType)} must be an interface"); | |
var concreteTypes = assembly.ExportedTypes.Select(t => t.GetTypeInfo()).Where(ti => ti.IsClass && !ti.IsAbstract); | |
foreach (var type in concreteTypes) | |
{ | |
var interfaces = type.ImplementedInterfaces.Select(i => i.GetTypeInfo()).ToArray(); | |
foreach (var @interface in interfaces.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == serviceType)) | |
{ | |
services.AddTransient(@interface.AsType(), type.AsType()); | |
} | |
foreach (var @interface in interfaces.Where(i => !i.IsGenericType && i.IsAssignableFrom(serviceType))) | |
{ | |
services.AddTransient(@interface.AsType(), type.AsType()); | |
} | |
} | |
return services; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment