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 Answer 1
"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;
}
}
ITest
parameters?