SimpleInjector生成多个实例

Lui*_*Rol 2 c# simple-injector

我在使用simpleInjector时遇到了一个奇怪的行为.

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

class A: IA, IB<D>{}
Run Code Online (Sandbox Code Playgroud)

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

foreach (var service in typeof(A).GetInterfaces())
{
    container.RegisterSingle(service, typeof(A));
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Yai*_*vet 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);
Run Code Online (Sandbox Code Playgroud)

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