Search code examples
c#eventsevent-handlingsimple-injector

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


I'm trying to subscribe to an event using Simple Injector. My class has:

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

With Ninject, it can be done with OnActivation():

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

How is this done with Simple Injector? I tried looking around, but only found content on IEventHandler/ICommandHandler implementations, none using C# events.


Solution

  • The equivalent to Ninject's OnActivation in Simple Injector is RegisterInitializer. Your code example translates to the following Simple Injector code:

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

    However, you should typically prefer using Constructor Injection as a mechanism to decouple classes over the use of events. You achieve the same amount of decoupling with Constructor Injection when you program against interfaces.

    Using Constructor Injection has the advantage that:

    • The container can analyse object graphs for you and detect any configuration pitfalls such as Captive Dependencies.
    • It improves discoverability, because an interface is less abstract than an event, which allows a reader to understand what the class is using and allows to easily navigate to an implementation.
    • It prevents Temporal Coupling.