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

我的未来我决定 提交于 2019-12-04 05:16:29

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!