问题
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 likeToConstructor(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