I have a series of classes where their interfaces inherit from a base interface. I want to try and DI them all in one go.
public interface ICrud<T> { }
public interface ITestService : ICrud<Test> { }
public interface IAnotherService : ICrud<Another> { }
public class TestService : ITestService { }
public class AnotherService : IAnotherService { }
I originally tried injecting all services within the assembly, but that proved dangerous and caused issues when trying to inject specific instances.
public static void AddAssemblyServices(this IServiceCollection services, Assembly assembly)
{
var serviceTypes = assembly.GetExportedTypes()
.Where(t => t.IsClass && !t.IsAbstract && t.GetInterfaces().Any());
foreach (var serviceType in serviceTypes)
{
var implementedInterfaces = serviceType.GetInterfaces();
foreach (var interfaceType in implementedInterfaces)
{
services.Add(new ServiceDescriptor(interfaceType, serviceType, ServiceLifetime.Transient));
}
}
}
I tried the following, but it hasn’t returned any results
public static void AddCrudServices(this IServiceCollection services)
{
var assembly = typeof(ICrud<>).Assembly;
var serviceTypes = assembly.GetExportedTypes()
.Where(t => t.IsClass && !t.IsAbstract && t.GetInterfaces().Contains(typeof(ICrud<>)));
AddAssemblyServices(services, serviceTypes);
}
>Solution :
Check if the interface is a constructed generic type and it’s generic type definition matches the searched one:
var serviceTypes = assembly.GetExportedTypes()
.Where(t => t is { IsClass: true, IsAbstract: false }
// here:
&& t.GetInterfaces().Any(i => i.IsConstructedGenericType && i.GetGenericTypeDefinition() == typeof(ICrud<>)))
.ToList();