Skip to content

Instantly share code, notes, and snippets.

@GetoXs
Last active March 2, 2024 06:06
Show Gist options
  • Save GetoXs/5caf0d8cfe6faa8a855c3ccef7c5a541 to your computer and use it in GitHub Desktop.
Save GetoXs/5caf0d8cfe6faa8a855c3ccef7c5a541 to your computer and use it in GitHub Desktop.
Register All Types (with Generic) in .NET Core DependencyInjection
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));
}
}
}
@ejaz-mirza
Copy link

DodajPlikHandler what is this type

@GetoXs
Copy link
Author

GetoXs commented Nov 2, 2020

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