.netdependency-injectionasp.net-core

.NET Core dependency injection -> Get all implementations of an interface


I have an interface called IRule and multiple classes that implement this interface. I want to use the .NET Core dependency injection Container to load all implementations of IRule, so all implemented rules.

Unfortunately I can't make this work. I know I can inject an IEnumerable<IRule> into my ctor of the controller, but I don't know how to register this setup in the Startup.cs


Solution

  • It's just a matter of registering all IRule implementations one by one; the Microsoft.Extensions.DependencyInjection (MS.DI) library can resolve it as an IEnumerable<T>. For instance:

    services.AddTransient<IRule, Rule1>();
    services.AddTransient<IRule, Rule2>();
    services.AddTransient<IRule, Rule3>();
    services.AddTransient<IRule, Rule4>();
    

    Consumer:

    public sealed class Consumer
    {
        private readonly IEnumerable<IRule> rules;
    
        public Consumer(IEnumerable<IRule> rules)
        {
            this.rules = rules;
        }
    }
    

    NOTE: The only collection type that MS.DI supports is IEnumerable<T>.