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

后端 未结 1 1462
梦谈多话
梦谈多话 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. For instance:

    services.AddTransient();
    services.AddTransient();
    services.AddTransient();
    services.AddTransient();
    

    Consumer:

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

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

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