Explain Dependency Injection with it's advantages with an example

 Posted by Rajnilari2015 on 6/21/2016 | Category: C# Interview questions | Views: 602 | Points: 40
Answer:

Let us consider the below code snippet

public Class A

{
public int EmpoloyeeID{get;set;}

public string EmpName{get;set;}

public void SomeFunction1(){/...../}

public void SomeFunction2(){/...../}

}
public Class B
{
A objA;
B(){ objA =new B(); }
public void PerformOperationofB(){ foo(objA); }
}
private void foo(A Aobj){
Aobj.SomeFunction1();//do something
Aobj.SomeFunction2();//do something
//rest of the code
}


The program apparently seems nice but has at least the below problems

1) code is not maintainable when it grows
2) Linear coding .. no OO design
3) No or less code reusability
4) Difficult to unit test
5) Highly coupled.

In-Order to mitigate the drawback, what we can do is to delegate the object creation to someone else (say interface). In other words, we are "inverting the control".

Let's see how

interface IMyInterface


{

int EmpoloyeeID{get;set;}

string EmpName{get;set;}

void SomeFunction1();

void SomeFunction2();

}
public Class A : IMyInterface
{
public int EmpoloyeeID{get;set;}
public string EmpName{get;set;}
public void SomeFunction1(){/..... concreate implementation .../}
public void SomeFunction2(){/..... concreate implementation .../}
}
public Class B
{
IMyInterface myInt;
B(IMyInterface myInt){ this.myInt = myInt; }
public void PerformOperationofB(){ foo(myInt); }
}
private void foo(IMyInterface myInt){
myInt.SomeFunction1();//do something
myInt.SomeFunction2();//do something
//rest of the code
}


The advantage of the approach

1) Unit testable code
2) Loosely coupled
3) Code re usability
4) Object creation is happening out the concrete implementation.
5) Maintainable code.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response