Home / .NET / Ninject constructor selection preview

Ninject constructor selection preview

Ninject 2.4 will introduce the ability to configure which constructor shall be used and to configure constructor arguments without having to use magic strings to define for which argument. In this post I will give a preview on how this works.


Since the constructor implicitly defines the type that is used as implementation type a new “To” overload has been introduced for this feature: ToConstructor. If a specific constructor shall be used this can be defined using:

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

As you see in the second example a IConstructorArgumentSyntax instance is passed to the expression. This parameter can be used to specify the parameters of the constructor.

The second usage of this feature is to specify constructor arguments without having to specify the parameter name using a magig string. Therefore you can pass the value to the expression. The expression is evaluated for each resolve. In case you need the context it is passed with the IConstructorArgumentSyntax as shown in the second example:

Bind<IMyService>().ToConstructor(_ => new MyService(new Foo(), 7));
Bind<IMyService>().ToConstructor(
    ctorArg => new MyService(ctorArg.Context.Kernel.Get<IFoo>("Foo1")));

Note that because the parameters are evaluated for each request each instance of MyService will get its own instance of Foo. In case you want foo to be a constant you have to define it outside of the binding as shown in the next expample:

var foo = new Foo();
Bind<IMyService>().ToConstructor(_ => new MyService(foo, 7));