Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to inject all classes where the derived interface inherits another interface of a specific type? C#

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading