c# - 使用单个接口(interface)注册多个实现

标签 c# c#-4.0 dependency-injection simple-injector

有没有一种方法可以在不使用模板接口(interface)的情况下使用 [simple-injector] 注册由多个具体类实现的单个接口(interface)?

假设我们有 2 个类 MyClass1Myclass2 并且这两个类都实现了 IInterface1

现在使用 [simple-injector] 我们无法做到这一点

container.Register<IInterface1, Myclass1>();
container.Register<IInterface1, Myclass2>();

将现有界面转换为模板界面在现有代码库上是一项艰巨的工作。希望那里有一些更简单的东西。

最佳答案

您可以使用 RegisterCollection 方法注册同一接口(interface)的多个实现(请参阅 documentation:配置要返回的实例集合)

所以你需要这样写:

container.Collection.Register<IInterface1>(typeof(Myclass1), typeof(Myclass2));

现在 Simple Injector 可以将 Interface1 实现的集合注入(inject)到您的构造函数中,例如:

public class Foo
{
    public Foo(IEnumerable<IInterface1> interfaces)
    {
        //...
    }
}

或者您可以使用 GetAllInstances 显式解析您的 IInterface1 实现:

var myClasses = container.GetAllInstances<IInterface1>();

关于c# - 使用单个接口(interface)注册多个实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17889385/

相关文章:

c# - 我可以为 HasMany 实体附加条件吗?

C# 语法——用逗号将字符串拆分为数组,转换为通用列表,并反转顺序

c# - 如何使用 Structuremap 创建单例 WCF 代理

c# - 如何将依赖项传递给自定义 .NET Core ILoggerProvider

c# - 如何对给定点之间的直线的所有像素位置进行采样?

c# - 我应该自己调用析构函数吗

c# - Windows 手机 7 : Other ways to remind the user of an event then alarm?

c# - RadioButton ContentStringFormat 不起作用

c# - 在控制台中显示时格式化 IEnumerable<double>

java - Dagger 与二传手进行测试