如何在不使用InjectAttribute的情况下使Ninject选择特定的构造函数? [英] How to make Ninject choose a specific constructor without using InjectAttribute?
问题描述
1)除了应用InjectAttribute
之外,有没有办法让Ninject在代码中选择特定的构造函数?
1) Is there a way to make Ninject select a specific constructor in code other than applying the InjectAttribute
?
2)另外,如何为构造函数的这些参数提供值?
2) Also, how do I supply values for these arguments of the constructor?
3)我可以在解析或创建对象时(即当我调用kernel.Get<T>()
时)覆盖这些参数值吗?
3) Can I override these argument values on resolution or creation of the object, i.e. when I call kernel.Get<T>()
?
推荐答案
有ToConstructor
绑定方法:
Bind<IMyService>().ToConstructor(
ctorArg => new MyService(ctorArg.Inject<IFoo>()));
您可以使用3种机制指定绑定值:
You can specify values on binding using 3 mechanisms:
- 为依赖项(
Bind<IFoo>().To<Foo>()
)创建绑定 - 指定构造函数参数(在绑定末尾添加
WithConstructorArgument(typeof(IFoo), new Foo())
) - 如果我没记错的话,还可以使用
ToConstructor
语法(例如ToConstructor(ctorArg => new MyService(myFoo));
)来指定它
- 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 likeToConstructor(ctorArg => new MyService(myFoo));
(另请参见 http://www.planetgeek. ch/2011/05/28/ninject-constructor-selection-preview/)
您可以通过传递 ConstructorArgument
,或者最好是 IParameter
)更改为分辨率:
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));
这篇关于如何在不使用InjectAttribute的情况下使Ninject选择特定的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!