SimpleInjector正在生成多个实例 [英] SimpleInjector multiple instances being generated

查看:321
本文介绍了SimpleInjector正在生成多个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I'm面临使用simpleInjector当一个奇怪的行为



下面的代码说明了我的情况:

  A类:IA,IB< D> {} 

然后,i'm注册它,每interface's例如一次,方法如下:在typeof运算

 的foreach(VAR服务(A ).GetInterfaces())
{
container.RegisterSingle(服务的typeof(A));
}



我的目标,就是要能够检索同一个实例(单), A的,无论是使用IA或IB。 IB代表一个EventListener接口。



把一个断点A's构造我可以看到它被称为两次当container.verify( )方法被调用,也就是说,不是在这里有一个单身I'm。



What's不对的情况?我需要的威胁泛型接口以不同的方式?


解决方案

注册多个接口与同实施



要坚持接口分离原则,它是
重要的保持接口收窄。虽然在大多数情况下实现
实现一个单一的接口,它有时是有益的对一个单一的实施
多个接口。下面是如何注册这个
的例子:




  //默认地将Impl工具IInterface1,IInterface2和IInterface3。 
变种注册=
Lifestyle.Singleton.CreateRegistration<默认地将Impl>(容器);

container.AddRegistration(typeof运算(IInterface1),注册);
container.AddRegistration(typeof运算(IInterface2),注册);
container.AddRegistration(typeof运算(IInterface3),注册);

VAR一个= container.GetInstance< IInterface1>();
变种B = container.GetInstance< IInterface2>();

//由于默认地将Impl是一个单,这两个请求返回相同的实例。
Assert.AreEqual(A,B);



参考:的注册多个接口具有相同的实现


I´m facing a strange behaviour when using simpleInjector.

The following code illustrates my scenario:

class A: IA, IB<D>{}

Then, i´m registering it, once per interface´s instance, as follows:

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

My goal, is to be able to retrieve the same instance (singleton), of A, using either IA or IB. IB stands for a eventlistener interface.

Putting a breakpoint on A´s constructor I can see it being called twice when the container.verify() method is called, meaning that I´m not having a singleton here.

What´s wrong with this scenario? Do I need to threat generics interface in a different fashion?

解决方案

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);

Reference: Register multiple interfaces with the same implementation

这篇关于SimpleInjector正在生成多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆