Skip to content

Instantly share code, notes, and snippets.

@thiagomajesk
Last active June 1, 2017 20:24
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 thiagomajesk/204ca7e602c3a1f1d5cc6f7b4ab42aa9 to your computer and use it in GitHub Desktop.
Save thiagomajesk/204ca7e602c3a1f1d5cc6f7b4ab42aa9 to your computer and use it in GitHub Desktop.
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