Dependency Injection – Understanding Dependency Injection

dependency-injection

I'm reading about dependency injection (DI). To me, it is a very complicated thing to do, as I was reading it was referencing inversion of control (IoC) as well and such I felt I was going to be in for a journey.

This is my understanding: Instead of creating a model in the class which also consumes it, you pass (inject) the model (already filled with interesting properties) to where it is needed (to a new class which could take it as a parameter in the constructor).

To me, this is just passing an argument. I must have miss understood the point? Maybe it becomes more obvious with bigger projects?

My understanding is non-DI (using pseudo code):

public void Start()
{
    MyClass class = new MyClass();
}

...

public MyClass()
{
    this.MyInterface = new MyInterface(); 
}

And DI would be

public void Start()
{
    MyInterface myInterface = new MyInterface();
    MyClass class = new MyClass(myInterface);
}

...

public MyClass(MyInterface myInterface)
{
    this.MyInterface = myInterface; 
}

Could some one shed some light as I'm sure I'm in a muddle here.

Best Answer

Well yes, you inject your dependencies, either through a constructor or through properties.
One of the reasons for this, is not to encumber MyClass with the details of how an instance of MyInterface needs to be constructed. MyInterface could be something that has a whole list of dependencies by itself and the code of MyClass would become ugly very fast if you had instantiate all the MyInterface dependencies inside of MyClass.

Another reason is for testing.
If you have a dependency on a file reader interface and you inject this dependency through a constructor in, say, ConsumerClass, that means that during testing, you can pass an in-memory implementation of the file reader to the ConsumerClass, avoiding the need to do I/O during testing.