Disable implicit binding/injection of non explicitly bound classes in Ninject 2+

随声附和 提交于 2019-12-04 11:41:26

问题


If you request an unbound object from NInject, then the default behaviour is (if a suitable constructor is available) appears to be to create an instance of the appropriate object.

I'd like to disable this behaviour (I had a difficult to debug issue because something was auto-bound instead of picking up my custom binding in a module). This question hints that it is possible, but I'm unable to find the answer from the NInject wiki.


回答1:


Remove the SelfBindingResolver from the kernel components after creation:

kernel.Components.RemoveAll<IMissingBindingResolver>();
kernel.Components.Add<IMissingBindingResolver, DefaultValueBindingResolver>();



回答2:


The following is a better, more direct way of removing the SelfBindingResolver, without assuming that the DefaultValueBindingResolver is the only other IMissingBindingResolver component:

kernel.Components.Remove<IMissingBindingResolver, SelfBindingResolver>();

It's possible the Remove<T, TImplementation>() method was only added in a recent version of Ninject, but this works for me using Ninject 3.2.2.0.



来源:https://stackoverflow.com/questions/14565380/disable-implicit-binding-injection-of-non-explicitly-bound-classes-in-ninject-2

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