简体   繁体   English

通过SimpleInjector注册单例并返回相同的实例,用于它实现的不同接口

[英]Registering a singleton via SimpleInjector and return the same instance, for different interfaces it implements

Imagine I have the below: 想象一下,我有以下内容:

public interface IocInterface1 { }

public interface IocInterface2 { }

public class IocImpl : IocInterface1, IocInterface2 { }

I would like that if I try to get any instance of the above classes/interfaces via IoC, I get the exact same instance, not one singleton per type. 我想如果我尝试通过IoC获取上述类/接口的任何实例,我得到完全相同的实例,而不是每个类型一个单例。 Example, b1 and b2 below should be true: 例如,下面的b1b2应该是真的:

_container.RegisterSingle<IocInterface1, IocImpl>();
_container.RegisterSingle<IocInterface2, IocImpl>();
_container.RegisterSingle<IocImpl, IocImpl>();

var test1 = _container.GetInstance<IocInterface1>();
var test2 = _container.GetInstance<IocInterface2>();
var test3 = _container.GetInstance<IocImpl>();

bool b1 = test1 == test2;
bool b2 = test2 == test3;

Is this possible? 这可能吗?

If you want to register a multiple types with the same registration then you will need a singleton registration object for your implementation type IocImpl . 如果要注册具有相同注册的多个类型,那么您将需要一个用于实现类型IocImpl的单例注册对象。

Then you need to use AddRegistration to add this registration for the different services: IocInterface1 , IocInterface2 etc.: 然后,您需要使用AddRegistration为不同的服务添加此注册: IocInterface1IocInterface2等:

var _container = new Container();
var registration =
    Lifestyle.Singleton.CreateRegistration<IocImpl, IocImpl>(_container);

_container.AddRegistration(typeof(IocImpl), registration);
_container.AddRegistration(typeof(IocInterface1), registration);
_container.AddRegistration(typeof(IocInterface2), registration);

as described in the documenation: Register multiple interfaces with the same implementation 如文档中所述: 使用相同的实现注册多个接口

Alternatively, you can also make a mapping using delegates: 或者,您也可以使用委托进行映射:

_container.RegisterSingle<IocImpl>();
_container.RegisterSingle<IocInterface1>(() => container.GetInstance<IocImpl>());
_container.RegisterSingle<IocInterface2>(() => container.GetInstance<IocImpl>());

In most cases both examples are functionally equivalent, but the former is preferred. 在大多数情况下,两个例子在功能上都是等同的,但前者是优选的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM