本文介绍了在Ninject中,如何使用Bind .... ToSelf()创建对象后在对象上运行自定义代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ninject的依赖项注入中,如果您像这样设置类与自身的绑定:

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

Bind<SomeClass>().ToSelf();

Ninject非常好地解决了SomeClass所具有的任何依赖关系,并为您提供了对象.我希望能够对每次创建新类时都会返回的SomeClass进行处理,就像后期处理事件一样.我可以使用.ToMethod(或ToFactoryMethod)绑定来显式地对其进行更新,但是我希望其所有依赖项都可以由Ninject预先解决.

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.

在Ninject 1.0/1.1中有什么方法可以做到这一点吗?

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

推荐答案

如果无法将要执行的代码放入构造函数中,则可以实现IInitializableIStartable.前者提供了一个Initialize()方法,该方法在所有注入完成之后被调用,而后者提供了一个Start()Stop()方法,分别在激活和停用期间调用.

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.

这篇关于在Ninject中,如何使用Bind .... ToSelf()创建对象后在对象上运行自定义代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 06:23