使用单个接口注册多个实现

时间:2013-07-26 19:24:30

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

有没有办法注册单个接口,该接口由多个具体类使用[simple-injector]并且不使用模板接口实现?

说我们有2个课程MyClass1Myclass2,这两个课程都在实施IInterface1

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

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

将现有接口转换为模板接口对现有代码库来说是一项艰巨的任务。希望有一些更容易的。

2 个答案:

答案 0 :(得分:14)

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

所以你需要写:

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

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

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

或者您可以使用IInterface1

明确解决GetAllInstances实施问题
var myClasses = container.GetAllInstances<IInterface1>();

答案 1 :(得分:0)

我遇到了同样的问题。我找到了一种解决方法,您可以根据使用者选择实现(我希望相反!)。请参见下面的示例:

container.RegisterConditional<IInterface1, Myclass1>(
            c => c.Consumer.ImplementationType == typeof(Myclass2Service));
container.RegisterConditional<IInterface1, Myclass2>(
            c => c.Consumer.ImplementationType == typeof(Myclass2Service));