2

Let's assume that I have the following interfaces and classes:

public interface ITest { }

public class Test : ITest { }

In NinjectWebCommon.cs:

kernel.Bind<ITest>().To<Test>();

And after this I want to use my ITest interface:

public class Vehicle
{
    private ITest _test = null;
    public Vehicle(ITest test)
    {
        this._test = test;
    }
}

public class TestVehicle
{
    public Vehicle vehicle = new Vehicle();//this will throw an error, because I haven't parameterless cnstructor in Vehicle class;
}

I know that in Vehicle class I can to do the parameterless constructor with the following way:

public Vehicle()
{
    this._test = DependencyResolver.Current.GetService<ITest>();
}

But it seems to be a bad practice and doesn't follow to dependency injection pattern.

So, how can I to solve this?

1
  • Why can't you replace the zero parameter constructor with one that takes an ITest parameters?
    – David Arno
    Commented Feb 1, 2017 at 8:33

1 Answer 1

2

"It's turtles all the way down".

Just as you're injecting ITest into Vehicle, you should inject Vehicle into TestVehicle - it doesn't matter that it's a concrete class rather than an interface, just let your DI framework do the work for you.

In fact, as you're using NInject, a self-binding will already have been created for Vehicle for you, so there's very little you need to do at all:

public class TestVehicle
{
  private readonly Vehicle _vehicle;

  public TestVehicle(Vehicle vehicle)
  {
    this._vehicle = vehicle;
  }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.