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

后端 未结 1 1457
梦谈多话
梦谈多话 2020-12-06 11:07

I have a interface called IRule and multiple classes that implement this interface. I want to uses the .NET Core dependency injection Container to load all implementation of

相关标签:
1条回答
  • 2020-12-06 11:33

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

    0 讨论(0)
提交回复
热议问题