Created
December 4, 2023 22:49
-
-
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
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
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