.NET Core依赖项注入->获取接口的所有实现 [英] .NET Core dependency injection -> Get all implementations of an interface
问题描述
我有一个称为IRule的接口和实现此接口的多个类。我想使用.NET Core依赖项注入容器来加载IRule的所有实现,因此要加载所有已实现的规则。
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 IRule, so all implemented rules.
不幸的是,我无法完成这项工作。我知道可以将 IEnumerable< IRule>
注入到控制器的ctor中,但是我不知道如何在Startup.cs中注册此设置。
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
推荐答案
只需要逐个注册所有 IRule
实现即可。 MS.Ext.DI库可以将其解析为 IEnumerable< T>
。
It's just a matter of registering all IRule
implementations one by one; the MS.Ext.DI library can resolve it as an IEnumerable<T>
.
services.AddTransient<IRule, Rule1>();
services.AddTransient<IRule, Rule2>();
services.AddTransient<IRule, Rule3>();
services.AddTransient<IRule, Rule4>();
这篇关于.NET Core依赖项注入->获取接口的所有实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!