Last active
March 2, 2024 06:06
-
-
Save GetoXs/5caf0d8cfe6faa8a855c3ccef7c5a541 to your computer and use it in GitHub Desktop.
Register All Types (with Generic) in .NET Core DependencyInjection
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 System; | |
using System.Linq; | |
using System.Reflection; | |
using Microsoft.Extensions.DependencyInjection; | |
public static class ServiceCollectionExtentions | |
{ | |
public static void AddAllTypes<T>(this IServiceCollection services | |
, Assembly[] assemblies | |
, bool additionalRegisterTypesByThemself = false | |
, ServiceLifetime lifetime = ServiceLifetime.Transient | |
) | |
{ | |
var typesFromAssemblies = assemblies.SelectMany(a => | |
a.DefinedTypes.Where(x => x.GetInterfaces().Any(i => i == typeof(T)))); | |
foreach (var type in typesFromAssemblies) | |
{ | |
services.Add(new ServiceDescriptor(typeof(T), type, lifetime)); | |
if (additionalRegisterTypesByThemself) | |
services.Add(new ServiceDescriptor(type, type, lifetime)); | |
} | |
} | |
public static void AddAllGenericTypes(this IServiceCollection services | |
, Type t | |
, Assembly[] assemblies | |
, bool additionalRegisterTypesByThemself = false | |
, ServiceLifetime lifetime = ServiceLifetime.Transient | |
) | |
{ | |
var genericType = t; | |
var typesFromAssemblies = assemblies.SelectMany(a => a.DefinedTypes.Where(x => x.GetInterfaces() | |
.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == genericType))); | |
foreach (var type in typesFromAssemblies) | |
{ | |
services.Add(new ServiceDescriptor(t, type, lifetime)); | |
if (additionalRegisterTypesByThemself) | |
services.Add(new ServiceDescriptor(type, type, lifetime)); | |
} | |
} | |
} |
DodajPlikHandler
is example file from project with you would like to search for types. It could be like: GenerateInvoiceCommand
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
DodajPlikHandler what is this type