mercredi 4 mai 2022

How to register services with dependency container services by reflection in c#

I have an interface IProcessor and multiple processors implementing this interface:

Processor1 : IProcessor
Processor2 : IProcessor

I want to inject these processors into a class like: IEnumerable<IProcessor> so that I can run them one by one.

I can register these one by one with the microsoft dependency injection container, but I want to do it by reflection so that a newly added processor is registered automatically.

var processorInterface = typeof(IProcessor);

var processors = Assembly.GetExecutingAssembly().GetTypes()
               .Where(t => processorInterface.IsAssignableFrom(t) && t.IsClass && 
               !t.IsAbstract && t.IsPublic);                  

foreach (var processor in processors)
{
    serviceCollection.AddScoped(processor);

    // Below line does not compile of course
    //serviceCollection.AddScoped<IProcessor, processor>());
}

But this doesn't work, I always get an empty list injected.





Aucun commentaire:

Enregistrer un commentaire