有没有一种方法可以注册一个由多个具体类实现的接口,使用simple-injector而不使用模板接口?
假设我们有两个类MyClass1和Myclass2,这两个类都实现了IInterface1
现在使用simple-injector我们无法做到这一点
container.Register<IInterface1, Myclass1>();
container.Register<IInterface1, Myclass2>();在现有的代码库中,将现有接口转换为模板接口是一项艰巨的工作。希望能有一些更容易的东西。
发布于 2013-07-27 03:47:32
您可以使用RegisterCollection方法注册同一接口的多个实现(请参阅documentation:配置要返回的实例集合)
所以你需要写下:
container.Collection.Register<IInterface1>(typeof(Myclass1), typeof(Myclass2));现在,简单注入器可以将一组Interface1实现注入到您的构造函数中,例如:
public class Foo
{
public Foo(IEnumerable<IInterface1> interfaces)
{
//...
}
}或者您可以使用GetAllInstances显式地解析您的IInterface1实现
var myClasses = container.GetAllInstances<IInterface1>();发布于 2019-08-21 05:46:16
我也面临着同样的问题。我找到了一个解决办法,你可以根据消费者选择实现(我希望是相反的!)。如下例所示:
container.RegisterConditional<IInterface1, Myclass1>(
c => c.Consumer.ImplementationType == typeof(Myclass2Service));
container.RegisterConditional<IInterface1, Myclass2>(
c => c.Consumer.ImplementationType == typeof(Myclass2Service));https://stackoverflow.com/questions/17889385
复制相似问题