有没有一种方法可以在不使用模板接口(interface)的情况下使用 [simple-injector] 注册由多个具体类实现的单个接口(interface)?
假设我们有 2 个类 MyClass1
和 Myclass2
并且这两个类都实现了 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/