Multiple Constructor Injection

The solution to a class having multiple constructors with NInject does not seem to work.

public class Class1 : IClass { public Class1(int param) {...} public Class1(int param2, string param3) { .. } } 

the following does not work:

 IClass1 instance = IocContainer.Get<IClass>(With.Parameters.ConstructorArgument("param", 1)); 

The hook in the module is simple and worked before I added an additional constructor: Bind () To () ;.

+1
source share
2 answers

The reason it doesn't work is because the argument arguments are not manually considered in the .ctor selection process. The values โ€‹โ€‹of .ctors are determined depending on how many parameters they have, which have a binding to the type of parameter. During activation, the manually enclosed .ctor arguments apply. Since you do not have bindings to int or string, they are not clogged. You can force scoring by adding the [Inject] attribute to the .ctor that you want to use.

+5
source

The problem you are facing is that Ninject selects .ctors based on the number of related options available to it. This means that Ninject basically does not understand overloading.

You can work around this problem by using the .ToConstructor () function in your bindings and combining it with the .Named () function. This allows you to create multiple bindings for the same class for different constructors with different names. It is a bit ragged, but it works.

I support my own software development blog, so it ended up being a post. If you need some sample code and a bit more explanation, you should check it out.

http://www.nephandus.com/2013/05/10/overloading-ninject/

+4
source

All Articles