
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 atleast 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 reusability
4) Object creation is happening out the concrete implementation.
5) Maintainable code.
This portion of the code
B(IMyInterface myInt){
this.myInt = myInt;
}
is the depenndency injection.
In real time, mostly we use for unit testing and internal API comunication from the concrete classes by using NInject (another DI tool) and while implementation of the Repository Pattern.
Let us know if that helps
--
Thanks & Regards,
RNA Team
Kumarkrishna184, if this helps please login to Mark As Answer. | Alert Moderator