dimanche 21 décembre 2014

Understanding Inversion of Control and Dependency Injection

I am learning the concept of IoC and DI. I checked a few blogs and below is my understanding:


A tight-coupling example without the use of IoC:



Public Class A
{
public A(int value1, int value2)
{
return Sum(value1, value2);
}

private int Sum(int a, int b)
{
return a+b;
}
}


After IoC:



Public Interface IOperation
{
int Sum(int a, int b);
}

Public Class A
{
private IOperation operation;

public A(IOperation operation)
{
this.operation = operation;
}

public void PerformOperation(B b)
{
operation.Sum(b);
}
}

Public Class B: IOperation
{
public int Sum(int a, int b)
{
return a+b;
}
}


The method PerformOperation in Class A is wrong. I guess, it is again tightly coupled as parameter is hard coded as B b.


In the above example, where is IoC as I can see only Dependency Injection in the constructor of Class A.


Please clear my understanding.


Aucun commentaire:

Enregistrer un commentaire