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));

About the author

Remo Gloor

My name is Remo Gloor and I’m working as a software architect at bbv Software Services AG in Zug, Switzerland. My first expiriences with computers were a a little boy with basic programming on a C64, later Pascal an C on an Intel 8080. After finishing my study in software engineering I started working with C#.

Currently, I'm one of two Main Developers of the well known Ninject IoC containers. My other interests beside Ninject are TDD, Scrum and software architecture in general.

4 comments

  • Maybe you should add the examples with nested constructors and passing in local variables. The examples we discussed yesterday.

  • Yes! You should also mention what happens when you want to pass in a constructor argument which is destined for a class deep down in the hierarchy…

    Thanks

  • This feature is not about passing constructor arguments at resolve time. It’s about static configured constructor arguments defined at configuration time of the kernel.

    But we can start a discussion if support for passing constructor arguments to deeper instances should be added to Ninject in the google group if this is desired.

By Remo Gloor

Recent Posts