0

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>()?

Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336

1 Answers1

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));
BatteryBackupUnit
  • 12,934
  • 1
  • 42
  • 68