Skip to content

Instantly share code, notes, and snippets.

@m-malkowski
Created June 18, 2018 09:07
Show Gist options
  • Select an option

  • Save m-malkowski/b007fccf7c7e3d4d62a6abe4ef413c0e to your computer and use it in GitHub Desktop.

Select an option

Save m-malkowski/b007fccf7c7e3d4d62a6abe4ef413c0e to your computer and use it in GitHub Desktop.
Working with built-in dependency injection of ASP .NET Core - finding and adding to container
public static class AttributeInjector
{
public static void AddInjectionByAttribute(this IServiceCollection services)
{
RegisterWithAttribute(ref services, typeof(InjectableSingletonAttribute));
RegisterWithAttribute(ref services, typeof(InjectableTransientAttribute));
RegisterWithAttribute(ref services, typeof(InjectableScopedAttribute));
}
private static void RegisterWithAttribute(ref IServiceCollection services, Type injectableAttribute)
{
foreach(var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
var allTypes = assembly.GetTypes();
var classesWithAttribute = allTypes.Where(t => t.IsClass && t.CustomAttributes.Any(a => a.AttributeType == injectableAttribute));
var an = classesWithAttribute.ToArray();
foreach (var implementationType in classesWithAttribute)
{
var interfaceType = allTypes.FirstOrDefault(t => t.IsInterface && t.Name.Substring(1) == implementationType.Name);
if (interfaceType == null) throw new Exception($"Failed to resolve interface for class {implementationType.Name}, unable to inject dependency!");
if (injectableAttribute == typeof(InjectableTransientAttribute))
services.AddTransient(interfaceType, implementationType);
if (injectableAttribute == typeof(InjectableScopedAttribute))
services.AddScoped(interfaceType, implementationType);
if (injectableAttribute == typeof(InjectableSingletonAttribute))
services.AddSingleton(interfaceType, implementationType);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment