Skip to content

Instantly share code, notes, and snippets.

@Robbware
Created December 4, 2023 22:49
Show Gist options
  • Save Robbware/b80c0af1d3d10fa77475824b645858a5 to your computer and use it in GitHub Desktop.
Save Robbware/b80c0af1d3d10fa77475824b645858a5 to your computer and use it in GitHub Desktop.
IServiceCollection extension to add all types of a particular type within the same assembly
using Microsoft.Extensions.DependencyInjection;
public static class DependencyInjectionHelper
{
public static IServiceCollection AddByType<T>(this IServiceCollection serviceCollection, ServiceLifetime serviceLifetime = ServiceLifetime.Transient)
{
var types = typeof(T).Assembly.GetTypes()
.Where(x => !x.IsAbstract && x.IsClass && x.GetInterface(typeof(T).Name) == typeof(T));
foreach (var type in types)
{
serviceCollection.Add(new ServiceDescriptor(typeof(T), type, serviceLifetime));
}
return serviceCollection;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment