SimpleInjector生成多个实例

时间:2014-01-01 18:00:59

标签: c# simple-injector

我在使用simpleInjector时遇到了一种奇怪的行为。

以下代码说明了我的方案:

class A: IA, IB<D>{}

然后,我正在为每个接口的实例注册一次,如下所示:

foreach (var service in typeof(A).GetInterfaces())
{
    container.RegisterSingle(service, typeof(A));
}

我的目标是能够使用IA或IB检索A的相同实例(单例)。 IB代表eventlistener接口。

在A的构造函数上设置断点我调用了container.verify()方法时可以看到它被调用了两次,这意味着我这里没有单例。

这种情况有什么问题?我是否需要以不同的方式威胁泛型界面?

1 个答案:

答案 0 :(得分:5)

  

使用相同的实现注册多个接口

     

要遵守接口隔离原则,重要的是   保持接口狭窄。虽然在大多数情况下实施   实现单一界面,有时可能是有益的   单个实现上的多个接口。这是一个例子   如何注册:

// 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