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

本文关键字:实现 接口 实例 返回 注册 SimpleInjector 单例 一个 通过 | 更新日期: 2023-09-27 18:12:14

假设我有以下内容:

public interface IocInterface1 { }
public interface IocInterface2 { }
public class IocImpl : IocInterface1, IocInterface2 { }

我希望,如果我试图通过IoC获得上述类/接口的任何实例,我得到完全相同的实例,而不是每个类型一个单例。例如,下面的b1b2应该为true:

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

这可能吗?

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

如果你想用相同的注册注册多个类型,那么你将需要为你的实现类型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);
用相同的实现注册多个接口

或者,您也可以使用委托创建映射:

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

在大多数情况下,这两个示例在功能上是相同的,但首选前者。