【问题标题】:Simple Injector - Subscribing to an event with the += operator (plus equals) like Ninject's OnActivationSimple Injector - 使用 += 运算符(加等于)订阅事件,例如 Ninject 的 OnActivation
【发布时间】:2017-04-19 16:34:37
【问题描述】:

我正在尝试使用 Simple Injector 订阅事件。我的班级有:

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 实现的内容,没有使用 C# 事件。

【问题讨论】:

    标签: c# events event-handling simple-injector


    【解决方案1】:

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

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

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

    使用构造函数注入的好处是:

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

    【讨论】:

    • 太棒了!很好的答案,我一定会重新考虑我设计的这一部分,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多