Injection of class with multiple constructors
Asked Answered
P

2

2

Resolving a class that has multiple constructors with NInject doesn't seem to work.

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

the following doesn’t seem to work:

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

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

Phylys answered 26/3, 2010 at 9:42 Comment(1)
Don't do DI with overloaded constructors. It introduces unwanted ambiguity: #2470602Cockpit
I
5

The reason that it doesn't work is that manually supplied .ctor arguments are not considered in the .ctor selection process. The .ctors are scored according to how many parameters they have of which there is a binding on the parameter type. During activation, the manually supplied .ctor arguments are applied. Since you don't have bindings on int or string, they are not scored. You can force a scoring by adding the [Inject] attribute to the .ctor you wish to use.

Ingalls answered 26/3, 2010 at 12:41 Comment(0)
S
4

The problem you're having is that Ninject selects .ctors based on the number of bound parameters available to it. That means that Ninject fundamentally doesn't understand overloading.

You can work around this problem by using the .ToConstructor() function in your bindings and combining it with the .Named() function. That lets you create multiple bindings for the same class to different constructors with different names. It's a little kludgy, but it works.

I maintain my own software development blog so this ended up being a post on it. If you want some example code and a little more explanation you should check it out.

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

Salcedo answered 10/5, 2013 at 20:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.