I’m trying to get my head around IoC w. dependency injection and I have followed this blogpost from Joel Abrahamsson: http://joelabrahamsson.com/entry/inversion-of-control-introduction-with-examples-in-dotnet
I have set up my projects like this:
- Model
- Interfaces
- Controllers
- DAL
And my classes is as follows:
Car
public class Car
{
public int Id { get; set; }
public string Brand { get; set; }
public string Year { get; set; }
}
CarController
public class CarController
{
private readonly ICar _carInterface;
public CarController(ICar car)
{
_carInterface = car;
}
public void SaveCar(Car car)
{
_carInterface.SaveCar(car);
}
}
ICar interface
public interface ICar
{
void SaveCar(Car car);
}
DbCar
public class DbCar: ICar
{
public void SaveCar(Car car)
{
throw new NotImplementedException();
}
}
Now, on the UI, I’m not sure what to do with this 😉 I can sure enough make the Car object that I need, but when new’ing up a CarController, it (of course) expects an ICar interface which I can’t give it.
I’ve got a feeling that I have misunderstood something along the way of reading Joels (great) article 🙂 And I was hoping that maybe someone could shed a light on what I have missed/misunderstood.
Any help/hint is greatly appreciated!
Thanks a lot in advance.
All the best,
Bo
It looks like
ICaris not an interface to a car. Rather it’s an interface to a repository for saving cars in. So it should be calledICarRepository(or possiblyIGarage.)You say:
Why not? You have an implementation,
DbCar. Why can’t you give it one of those?You asked in a comment about this expression:
Specifically that by writing that line of code, you’ve tied the controller to a specific implementation of the car repository.
That’s true, but only in that case. Somewhere else in a unit test you could write:
The
CarControllerclass is an independent module, and its dependency on other things is clear from its constructor’s parameter list.IoC or “dependency injection” frameworks are libraries that provide a standard way to construct classes such as
CarController, so that the parameters it needs will be specified in a config file. But that’s probably overkill for a simple app.