简单注入器 - 使用 += 运算符(加上等于)订阅事件,例如 Ninject 的 OnActivation

Simple Injector - Subscribing to an event with the += operator (plus equals) like Ninject's OnActivation

我正在尝试使用 Simple Injector 订阅一个事件。我的 class 有:

public class MyClass
{
    public event Action<MyClass> SomeEvent;
    //...
}

用Ninject可以用OnActivation():

Bind<MyClass>().ToSelf()
    .OnActivation((context, myObj) =>
    {
        myObj.SomeEvent += MyStaticEventHandler.Handle; // for static
        // or...
        myObj.SomeEvent += context.Kernel.Get<MyEventHandler>().Handle; // for non-static
    });

如何使用 Simple Injector 完成这项工作?我试着环顾四周,但只找到了 IEventHandler/ICommandHandler 实现的内容,none 使用 C# 事件。

在 Simple Injector 中等价于 Ninject 的 OnActivationRegisterInitializer。您的代码示例转换为以下简单注入器代码:

container.Register<MyClass>();
container.RegisterInitializer<MyClass>(myObj =>
{
    myObj.SomeEvent += MyStaticEventHandler.Handle; // for static
    // or...
    myObj.SomeEvent += container.GetInstance<MyEventHandler>().Handle; // for non-static
});

但是,您通常应该更喜欢使用构造函数注入作为一种机制来解耦 classes 而不是使用事件。当您 针对接口 编程时,您可以通过构造函数注入实现相同数量的解耦。

使用构造函数注入的优点是:

  • 容器可以为您分析对象图并检测任何配置缺陷,例如 Captive Dependencies
  • 它提高了可发现性,因为接口不如事件抽象,这允许 reader 了解 class 正在使用什么,并允许轻松导航到实现。
  • 它可以防止 Temporal Coupling