In Ninject, how can I run my own code for an object after I create it using Bind <..>. ToSelf ()?

In a Ninject dependency injection, if you configured the class binding to yourself as follows:

 Bind<SomeClass>().ToSelf(); 

Ninject very nicely resolves any dependencies SomeClass has and returns the object back. I want to be able to do something with SomeClass, it returns every time it creates a new one, so this is an event after processing. I could use the .ToMethod (or ToFactoryMethod) binding to explicitly update it, but I would like all of its dependencies to be resolved by Ninject in advance.

It would be nice to do something like:

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

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

+6
source share
2 answers

If you cannot put the code you want to execute in the constructor, you can implement IInitializable or IStartable . The former provides the Initialize() method, which is called upon completion of the entire injection, and the latter provides both the Start() and Stop() methods, which are called during activation and deactivation, respectively.

+11
source

I ran into the same problem, but I could not use the Nate solution because I could not make an implementation of type IInitializable . If you are in a similar boat, you can use .OnActivation and not change the rules for the target types:

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

You can see how we call some arbitrary initialization method ( MyInitialize ) when the class is activated (instance).

This has the advantage that you do not bake a hard dependency on Ninject in your own classes (other than your modules, of course), thereby allowing your types to remain agnostically relative to the DI framework you end up using.

+9
source

All Articles