Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ninject, how can I run custom code on an object after it is created with Bind<..>.ToSelf()?

In Ninject's dependency injection, if you set up a binding of a class to itself like so:

Bind<SomeClass>().ToSelf();

Ninject very nicely resolves any dependencies SomeClass has and gives you the object back. I want to be able to do something to the SomeClass it returns every time it creates a new one, so like a post-processing event. I could use the .ToMethod (or ToFactoryMethod) binding to explicitly new it up, but I would like all its dependencies resolved by Ninject beforehand.

It wouldu be nice to do something like:

Bind<SomeClass>()
    .ToSelf()
    .After(sc => sc.MethodIWantToCall()); // then after here, Ninject returns the object.

Is there some way to do this in Ninject 1.0/1.1?

like image 727
ZeroBugBounce Avatar asked Jul 24 '09 17:07

ZeroBugBounce


2 Answers

If you can't put the code you want to execute in the constructor, you can implement IInitializable or IStartable. The former provides an Initialize() method that gets called after all injection has completed, and the latter provides both a Start() and Stop() method, called during activation and deactivation, respectively.

like image 113
Nate Kohari Avatar answered Nov 14 '22 08:11

Nate Kohari


I ran into the same problem, but I could not use Nate's solution because I couldn't make the type implement IInitializable. If you're in a similar boat, you can use .OnActivation and avoid having to modify the definition of the target types:

Bind<SomeClass>().ToSelf().OnActivation(x => ((SomeClass)x).MyInitialize());

You can see how we call some arbitrary initialization method (MyInitialize) upon activation (instantiation) of the class.

This has the advantage of not baking in a hard dependency to Ninject in your own classes (aside from your modules, of course), thus allowing your types to remain agnostic about the DI-framework you end up using.

like image 10
Kirk Woll Avatar answered Nov 14 '22 10:11

Kirk Woll