Sunday, June 3, 2012

Explain Dependency Injection with an example

One of the very common interview questions, asked these days. This is the most common approach used today to solve dependencies between objects. In many of the enterprise class ASP.NET application, Dependency Injection is a common standard to follow. Let us understand Dependency Injection with an example.


In the example above, Employee class depends on EmployeeDAL class to get the data from the database. In GetAllEmployees() method of the Employee class, we create an instance of the EmployeeDAL (Employee Data Access Layer) class and then invoke SelectAllEmployees() method. This is tight coupling, EmployeeDAL is tightly copuled with the Employee class. Everytime the EmployeeDAL class changes, the Employee class also needs to change. EmployeeDAL cannot be mocked and hence unit testing becomes cumbersome and time consuming.

The same example can be re-written using dependency injection as shown below. First thing to notice is that, we are using interface types instead of concrete types. Using interfaces help us to plugin any implemenation of the interface, with less or no code modification at all. We are not creating the instance of the EmployeeDAL in the Employee class, instead we are passing it as a parameter to the constructor of the Employee class. As, we are injecting an instance of a class into a class that depends on it, we can call this process as Dependency Injection.


Dependency Injection is of 2 types.
1. Constructor Injection
2. Setter Injection.

We have already seen how to use Constructor Injection in the example above. An, example for Setter Injection is shown below. We are injecting an object instance through the Setter property, instead of a constructor. Hence, we call Setter Injection. It is very important to use the property EmployeeDataObject to access the instance of IEmployeeDAL, rather than the private variable employeeDAL. The property checks to see if employeeDAL is null, and throws the exception accordingly.

1 comment:

  1. Great, thanks for sharing this. Also, check this out if you are looking for professional website or logo design services:


    Buy Logo

    ReplyDelete