我在使用 simpleInjector 时遇到了一个奇怪的行为。
以下代码说明了我的场景:
class A: IA, IB<D>{}
然后,我正在为每个接口(interface)实例注册一次,如下所示:
foreach (var service in typeof(A).GetInterfaces())
{
container.RegisterSingle(service, typeof(A));
}
我的目标是能够使用 IA 或 IB 检索 A 的相同实例(单例)。 IB 代表事件监听器接口(interface)。
在调用 container.verify() 方法时,在 A 的构造函数上放置一个断点我可以看到它被调用了两次,这意味着我在这里没有单例。
这种情况有什么问题?我是否需要以不同的方式威胁泛型接口(interface)?
最佳答案
Register multiple interfaces with the same implementation
To adhere to the Interface Segregation Principle, it is important to keep interfaces narrow. Although in most situations implementations implement a single interface, it can sometimes be beneficial to have multiple interfaces on a single implementation. Here is an example of how to register this:
// Impl implements IInterface1, IInterface2 and IInterface3.
var registration =
Lifestyle.Singleton.CreateRegistration<Impl>(container);
container.AddRegistration(typeof(IInterface1), registration);
container.AddRegistration(typeof(IInterface2), registration);
container.AddRegistration(typeof(IInterface3), registration);
var a = container.GetInstance<IInterface1>();
var b = container.GetInstance<IInterface2>();
// Since Impl is a singleton, both requests return the same instance.
Assert.AreEqual(a, b);
引用:Register multiple interfaces with the same implementation
关于c# - 正在生成 SimpleInjector 多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20871543/