Simple injector - subscribing to an event with the + = (plus equals) operator, like Ninject OnActivation

I am trying to subscribe to an event using Simple Injector. My class:

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

      

With Ninject, this 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 a simple injector? I tried looking around but found content only in implementations of IEventHandler

/ ICommandHandler

but not using C # events.

+3


source to share


1 answer


OnActivation

Simple Injector's Ninject equivalent is RegisterInitializer

. Your example code translates into 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
});

      

Typically, however, you should use the Injection constructor as a mechanism to separate classes into event usage. 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 parse graphs of objects for you and detect any configuration errors like Captive Dependencies .
  • This improves discoverability because the interface is less abstract than the event, allowing the reader to understand what the class is using and making it easy to jump to implementation.
  • It prevents temporary communication .
+3


source







All Articles