How to make Ninject choose a specific constructor without using InjectAttribute?

佐手、 提交于 2019-12-12 05:15:57

问题


1) Is there a way to make Ninject select a specific constructor in code other than applying the InjectAttribute?

2) Also, how do I supply values for these arguments of the constructor?

3) Can I override these argument values on resolution or creation of the object, i.e. when I call kernel.Get<T>()?


回答1:


There's the ToConstructor binding method:

Bind<IMyService>().ToConstructor(
    ctorArg => new MyService(ctorArg.Inject<IFoo>()));

You can specify values on binding using 3 mechanisms:

  • create a binding for the dependency (Bind<IFoo>().To<Foo>())
  • specify a constructor argument (add a WithConstructorArgument(typeof(IFoo), new Foo()) to the end of the binding)
  • if i remember correctly, you can also specify it in the ToConstructor syntax like ToConstructor(ctorArg => new MyService(myFoo));

(Also see http://www.planetgeek.ch/2011/05/28/ninject-constructor-selection-preview/)

You can specify values on resolution by passing a ConstructorArgument or, preferrably, a TypeMatchingConstructorArgument (or some custom IParameter) to the resolution:

IResolutionRoot.Get<IMyService>(new TypedConstructorArgument(
    typeof(IFoo),
    (ctx, target) => myFooInstance));


来源:https://stackoverflow.com/questions/35308511/how-to-make-ninject-choose-a-specific-constructor-without-using-injectattribute

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