Nik*_*Nik 7 .net dependency-injection asp.net-core
我有一个名为IRule的接口和多个实现此接口的类.我想使用.NET Core依赖注入Container来加载IRule的所有实现,因此所有实现的规则.
不幸的是我无法做到这一点.我知道我可以注入一个IEnumerable<IRule>控制器的ctor,但我不知道如何在Startup.cs中注册这个设置
Seb*_*ian 20
对于其他正在寻找答案的人。您还可以检查程序集并注册实现特定接口的所有类:
// Get all implementations of IRule and add them to the DI
var rules = typeof(Program).Assembly.GetTypes()
.Where(x => !x.IsAbstract && x.IsClass && x.GetInterface(nameof(IRule)) == typeof(IRule));
foreach (var rule in rules)
{
services.Add(new ServiceDescriptor(typeof(IRule), rule, ServiceLifetime.Transient));
// Replace Transient with whatever lifetime you need
}
Run Code Online (Sandbox Code Playgroud)
这也将为IEnumerable<IRule>依赖注入的每个类提供一个。此解决方案的优点是您不需要将每个规则添加到依赖项注入中。您只需将新的实现添加IRule到您的项目中,它将自动注册。
Ste*_*ven 13
这只是一个接一个地注册所有IRule实现的问题; MS.Ext.DI库可以将其解析为IEnumerable<T>.
services.AddTransient<IRule, Rule1>();
services.AddTransient<IRule, Rule2>();
services.AddTransient<IRule, Rule3>();
services.AddTransient<IRule, Rule4>();
Run Code Online (Sandbox Code Playgroud)
塞巴斯蒂安和丹尼施综合回答:
var rules = Assembly.GetExecutingAssembly().GetTypes()
.Where(x => !x.IsAbstract && x.IsClass && typeof(IRule).IsAssignableFrom(x));
foreach (var rule in rules)
{
services.Add(new ServiceDescriptor(typeof(IRule), rule, ServiceLifetime.Transient));
}
Run Code Online (Sandbox Code Playgroud)
另请注意,您可以使用执行程序集来搜索类型。
| 归档时间: |
|
| 查看次数: |
4235 次 |
| 最近记录: |