8

想象一下我有以下内容:

public interface IocInterface1 { }

public interface IocInterface2 { }

public class IocImpl : IocInterface1, IocInterface2 { }

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

这可能吗?

4

1 回答 1

11

如果您想使用相同的注册注册多个类型,那么您将需要一个单例注册对象作为您的实现类型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);

如文档中所述:使用相同的实现注册多个接口

或者,您也可以使用委托进行映射:

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

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

于 2013-05-03T15:58:38.790 回答