Light Version for web
What is Dependency Injection and Inversion of Control?
What is Dependency Injection and Inversion of Control?
When I started my professional career with a company here in Pakistan, I was directed by my Team Lead to Inject Dependency in the project. And I was like 🙁 What the heck is that? Then an angel came to me and said "Let me google that for you" and I said, "No thanks, I can do that for myself". Then I started googling, and guess what? after googling and reading from several blog posts I finally came to nowhere. At the exact same spot of where I started. I was really tensed, but I somehow managed to ditch my Team Lead. Yeah ! ( Give me high five.. \m/ ) And guess what? That same guy (me) now going to teach you what exactly is this Dependency Injection and Inversion of Control is. Please bear with me, and read full post you may love it 😉 Let's start then!

Depedency Injection and IoC

Let's suppose you are developing a Calculator program, and you wrote a sum function like this:
 function int Sum(){
      return (2+2);
Now you have that function, and from somewhere you called that function to get the Sum of two numbers. And you get the output:
Sum is = 4
And every time when you need Sum of two numbers you call that function but the function always returns you 4. And you are like 🙁 Why are you giving me the same output each time? Why? Because your output value is dependent on the inner implementation of the function which will always return (2+2) actually you don't have any control to the function (while calling) the control of the returned value is dependent on the function. And now you decided to change the implementation of the function like this:
 function int Sum(int a, int b){
      return (a+b);
Now you redefined the structure of the function and take all the controls that he have to the caller. you basically inverted the control from inside to the outside of the function. Now your output will be controlled by the caller arguments. You inverted the control so this is called Inversion of Control (IoC) Now, as your function is now parameterized and you can inject any value as arguments and you will get the sum. Passing the values as arguments are basically called as Depedency Injection. You are injecting the values to the function and you will get the required sum of those arguments.