.NET Core 依赖注入 ->获取接口的所有实现 [英] .NET Core dependency injection -> Get all implementations of an interface

查看:95
本文介绍了.NET Core 依赖注入 ->获取接口的所有实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 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 注入控制器的 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实现一一注册即可;Microsoft.Extensions.DependencyInjection (MS.DI) 库可以将其解析为 IEnumerable.例如:

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>();

消费者:

public sealed class Consumer
{
    private readonly IEnumerable<IRule> rules;

    public Consumer(IEnumerable<IRule> rules)
    {
        this.rules = rules;
    }
}

注意:MS.DI 支持的唯一集合类型是 IEnumerable.

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

这篇关于.NET Core 依赖注入 ->获取接口的所有实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆