c# - 正在生成 SimpleInjector 多个实例

标签 c# simple-injector

我在使用 simpleInjector 时遇到了一个奇怪的行为。

以下代码说明了我的场景:

class A: IA, IB<D>{}

然后,我正在为每个接口(interface)实例注册一次,如下所示:

foreach (var service in typeof(A).GetInterfaces())
{
    container.RegisterSingle(service, typeof(A));
}

我的目标是能够使用 IA 或 IB 检索 A 的相同实例(单例)。 IB 代表事件监听器接口(interface)。

在调用 container.verify() 方法时,在 A 的构造函数上放置一个断点我可以看到它被调用了两次,这意味着我在这里没有单例。

这种情况有什么问题?我是否需要以不同的方式威胁泛型接口(interface)?

最佳答案

Register multiple interfaces with the same implementation

To adhere to the Interface Segregation Principle, it is important to keep interfaces narrow. Although in most situations implementations implement a single interface, it can sometimes be beneficial to have multiple interfaces on a single implementation. Here is an example of how to register this:

// Impl implements IInterface1, IInterface2 and IInterface3.
var registration =
    Lifestyle.Singleton.CreateRegistration<Impl>(container);

container.AddRegistration(typeof(IInterface1), registration);
container.AddRegistration(typeof(IInterface2), registration);
container.AddRegistration(typeof(IInterface3), registration);

var a = container.GetInstance<IInterface1>();
var b = container.GetInstance<IInterface2>();

// Since Impl is a singleton, both requests return the same instance.
Assert.AreEqual(a, b);

引用:Register multiple interfaces with the same implementation

关于c# - 正在生成 SimpleInjector 多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20871543/

相关文章:

c# - 我需要在 C# .Net 中创建一个线程安全的静态变量

c# - 如何以编程方式设置对 Windows 服务的权限?

C# 使用 FTP 服务器目录填充 TreeView

c# - 安装 Google Cardboard Unity SDK 后,"Cardboard"未在 Unity Android 选项中显示为选项

c# - 在哪里以及如何获得 Simple Injector 容器?

c# - 在 Simple Injector 中注册时设置收集项目的 Lifestyle

c# - 如何使用 Simple Injector 从 ValidationContext 获取服务?

c# - 如何处理运行 ASP.NET 应用程序时遇到的错误

c# - WebApi + 简单注入(inject)器 + OWIN

c# - 简易喷油器 : Injecting a property in a base class