Tuesday, July 28, 2015

What is Dependency Injection?

Dependency Injection is a software design pattern which is used to improve testability of applications. Dependency Injection loosely couples the various components of the application thereby improve testability of the various components independently.

If the objects to be used in a class are initialized locally in the class, then it creates a dependency and makes the objects tightly bound to the class. The below class is an example without using Dependency Injection, notice that the objEmpRepository object is initialized within the class, hence it is tightly bound to the class.
class clsEmployee
{
          GetEmployeeDetails(int employeeID)
          {
                    EmployeeRepository objEmpRepository = new EmployeeRepository();
                   objEmpRepository.GetEmployeeDetails(employeeID);
          }
}

Dependency injection aims in creating the objects needed for the class from an external source and pass them as parameters to the class, this way we can control the objects used by the class, and can test the behaviors of the class for various scenarios by passing appropriate objects as parameters to the class.

In the below example, we have the same example re-written using Dependency Injection, notice that the objRepository object is passed as parameter to the constructor of the class, we can pass different parameters to the same class and test the class for  various combinations, thereby improving testability.

class clsEmployee
{
          EmployeeRepository objEmpRepository
          clsEmployee(EmployeeRepository objRepository)
          {
                   objEmpRepository = objRepository;
          }
          //
          GetEmployeeDetails(int employeeID)
          {
                   objEmpRepository.GetEmployeeDetails(employeeID);
          }
}

To summarize, Dependency Injection aims in injecting the objects, to make various components of an applications / system loosely coupled, this enables us to independently test the various components independently for various scenarios.

Search Flipkart Products:
Flipkart.com

No comments: