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.
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: