假设我有以下内容:
public interface IocInterface1 { }
public interface IocInterface2 { }
public class IocImpl : IocInterface1, IocInterface2 { }
如果我尝试通过 IoC 获取上述类/接口(interface)的任何实例,我希望得到完全相同的实例,而不是每种类型一个单例。例如,下面的 b1
和 b2
应该为真:
_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;
这可能吗?
最佳答案
如果您想使用相同的注册来注册多个类型,那么您需要为您的实现类型 IocImpl
注册一个单例注册对象。
然后您需要使用AddRegistration
为不同的服务添加此注册:IocInterface1
、IocInterface2
等:
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);
如文档中所述:Register multiple interfaces with the same implementation
或者,您也可以使用委托(delegate)进行映射:
_container.RegisterSingle<IocImpl>();
_container.RegisterSingle<IocInterface1>(() => container.GetInstance<IocImpl>());
_container.RegisterSingle<IocInterface2>(() => container.GetInstance<IocImpl>());
在大多数情况下,这两个示例在功能上是等效的,但前者是首选。
关于c# - 通过 SimpleInjector 注册单例并返回相同的实例,对于它实现的不同接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16362691/