Skip to main content

Understanding 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.

MyDaftQuestions
  • 1.9k
  • 4
  • 16
  • 15