问题
我正在尝试使用 DryIoc 注册一个单例,但容器返回了我的单例类的多个实例。单例类注册为多个不同服务接口(interface)的实现类型。当从 DryIoc 请求任何上述服务接口(interface)时,我希望得到我的单例类的相同实例,但那没有发生,我不知道为什么。
一个例子
这是我正在尝试做的一个基本示例。在此示例中,我有一个类 Foo
,我想将其用作接口(interface) IFoo
和 IBar
的单例实现。换句话说,当从容器中解析出 IFoo
或 IBar
时,我希望返回相同的 Foo
实例。
服务接口(interface)
interface IFoo
{
}
interface IBar
{
}
单例(实现)类
class Foo : IFoo, IBar
{
}
测试
Container container = new Container();
container.Register<IFoo, Foo>(Reuse.Singleton);
container.Register<IBar, Foo>(Reuse.Singleton);
object foo = container.Resolve<IFoo>();
object bar = container.Resolve<IBar>();
Assert.AreSame(foo, bar); // Why does this fail?
考虑的解决方案
我考虑过使用 DryIoc 的 RegisterInstance
方法,但这需要手动创建类,我正在努力避免这种情况,因为与上面的简化示例不同,真实世界的类有其自身的依赖性。
最佳答案
Register
方法向容器添加单独/独立的注册。您需要明确说明对多个服务使用相同的注册。
选项 1:RegisterMany
// registers with Foo interfaces and itself. Remove @nonPublicServiceTypes to restrict for public types
container.RegisterMany<Foo>(Reuse.Singleton, nonPublicServiceTypes: true);
Assert.AreSame(container.Resolve<IFoo>(), container.Resolve<IBar>());
选项 2:RegisterMapping
container.Register<IFoo, Foo>(Reuse.Singleton);
container.RegisterMapping<IBar, IFoo>(); // maps to the IBar registration
Assert.AreSame(container.Resolve<IFoo>(), container.Resolve<IBar>());
其他:
按照@Fyodor 的回答手动委托(delegate)解决方案。
关于c# - 使用 DryIoc 创建具有多个服务注册的单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39214220/