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

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>.

Leave a Comment