c# - 通过 SimpleInjector 注册单例并返回相同的实例,对于它实现的不同接口(interface)

标签 c# dependency-injection inversion-of-control ioc-container simple-injector

假设我有以下内容:

public interface IocInterface1 { }

public interface IocInterface2 { }

public class IocImpl : IocInterface1, IocInterface2 { }

如果我尝试通过 IoC 获取上述类/接口(interface)的任何实例,我希望得到完全相同的实例,而不是每种类型一个单例。例如,下面的 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;

这可能吗?

最佳答案

如果您想使用相同的注册来注册多个类型,那么您需要为您的实现类型 IocImpl 注册一个单例注册对象。

然后您需要使用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);

如文档中所述: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/

相关文章:

dependency-injection - Swift 的对象框架宏

go - 接口(interface)中的相同结构

c# - 没有实现 UoW 或存储库的 EF 是否正确?

.net - Windows 窗体中的 MVP 和 IOC?

c# - 如何避免服务定位器反模式?

c# - 一些 NGit 东西阻​​止 C# 应用程序正确关闭

c# - 在另一个进程中处理 WCF 事件

java - 使用 Mockito 在注入(inject)的服务类中注入(inject)对象

c# - Microsoft.Net.Compilers 的目的是什么?

c# - Mysql C# 无法连接到主机,但它可以