Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 400
rouan Avatar asked Oct 28 '25 16:10

rouan


2 Answers

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.

like image 106
Husein Roncevic Avatar answered Oct 31 '25 13:10

Husein Roncevic


You can avoid setting AllowNullInjection globally while still injecting a parameter only when a binding exists by configuring your binding like this:

Kernel.Bind<IMyClass>()
      .To<MyClass>()
      .WithConstructorArgument(typeof(IServiceThree), c => c.Kernel.TryGet<IServiceThree>());
like image 21
Dark Daskin Avatar answered Oct 31 '25 12:10

Dark Daskin