rouan rouan - 1 year ago 96
C# Question

How do I tell Ninject not to inject one of my constructor parameters?

If I have the following:

public MyClass(IServiceOne serviceOne, IServiceTwo serviceTwo, IServiceThree serviceThree = null)
this.serviceOne = serviceOne;
this.serviceTwo = serviceTwo;
this.serviceThree = serviceThree ?? new ServiceThree("some-info");

How can I tell Ninject to bind the first two arguments, but not the one of type IServiceThree? Is this even possible?

The reason I want serviceThree as a constructor argument is for testability - I need to be able to inject a mock from my tests.

Answer Source

If you don't plan to use constructor injection then you might as well remove it from the constructor arguments list and initialize it manually the way you do it. In other words, just pass two arguments instead of three.

UPDATE: What you could do is to inject null value. As far as I remember you would have to do something like following:

_kernel.Settings.AllowNullInjection = true;

Then you can remove the binding for the third argument if it exists.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download