Using Dependency Injection in MVC Application


In this article we are going to focus on Using Dependency Injection in MVC 4 Application. We we also see what is loose coupling and how Dependency Injection helps in maintaining the loosely coupled code.

In this article we are going to focus on Using Dependency Injection in MVC 4 Application

About Dependency Injection

1. It is used to create loosely coupled systems.
2. It is also known as Inversion of Control(IoC).
3. Here we remove any dependencies on concrete classes from our component by passing the implementation of the required interfaces to the constructor of the class at runtime.
4. It enforces strict separation between different parts of the application.
5. It also makes unit testing simple and easy.

Let us see Why and How Dependency Injection is used:

One of the most important concept of MVC is that it enables separation of concerns and the components should be as independent as possible and it should have manageable interdependencies

Loose Coupling

Each component of our application is independent and it deals with other areas of our application through abstract interfaces.

Why Loose Coupling

1. We can modify our application for any changes easily
2. It also makes testing easy.

Let us consider an example of a EmailService component which is responsible for sending emails. We are going to create an interface IEmailService which will define all the public functions required to send an email. This interface will be implemented by our EmailService component.

If any other component of our application needs to send email, For Example: UpdateDataService(Modification of some critical data by some user), can send email by referring to the methods of the interface. Here There is no direct dependency between EmailService and UpdateDataService but both of them depend on IEmailService.

Biggest advantage of this approach is that We can replace EmailService with another e-mail provider or even a mock implementation for testing purpose.

Implementing Dependency Injection concept
Let us consider below example where we are creating objects of concrete classes to get an interface implementation. Observe that the UpdateDataService class depends on IEmailService interface and EmailService class which is sort of tight coupling between UpdateDataService class and EmailService


public interface IEmailService
{
void SendEmail();
}

public class EmailService : IEmailService
{

public void SendEmail()
{
//code to send email
}
}
///
/// Configure and send emails through IEmailService interface.
/// UpdateDataService class depends on IEmailService interface and EmailService class
///

public class UpdateDataService
{
public void UpdateData()
{
IEmailService emailService = new EmailService();
//invoke interface methods to configure email settings...
emailService.SendEmail();
}
}

We need a way to obtain objects that implement a given interface without creating the implementing object directly. Correct solution to this issue is Dependency Injection.

Dependency Injection is a design pattern which will make our code loosely coupled by adding the IEmailService interface to our code.

In the below code we are removing dependencies from the UpdateDataService class.

public class UpdateDataService
{
private IEmailService emailService;

public UpdateDataService(IEmailService objEmailService)
{
emailService = objEmailService;
}
public void UpdateData()
{
//invoke interface methods to configure email settings...
emailService.SendEmail();
}
}


Now we have removed the dependency between UpdateDataService and EmailService by adding a constructor to the UpdateDataService class that needs an object that implements the IEmailService interface. Please note that it does not need to know anything about the object and it does not even create it.

Here There is no compile-time dependency between the UpdateDataService class and the class that implements the interfaces it depends on. The dependencies are injected into the UpdateDataService class at runtime. In our case, object of any class that implements the IEmailService interface will be created and passed to the UpdateDataService class constructor during instantiation.

Dependency Injection concept in an MVC application

Let us implement Dependency Injection concept in an MVC application.

We are going to create a controller class called as EmployeeController, that uses the repository EmployeeRepository for saving data without directly coupling EmployeeController and EmployeesRepository together.

Step 1: Create an interface "IEmployeesRepository" that decouples our two classes.

interface IEmployeesRepository
{
void AddEmployee(Employee employee);
Employee GetEmployeeByName(string name);
void SaveChanges();
}

Step 2: Create a EmployeesRepository class that implements the IEmployeesRepository interface

public class EmployeesRepository : IEmployeesRepository
{
public void AddEmployee(Employee employee)
{
// To-Do: code to Add Employee
}

public Employee GetEmployeeByName(string name)
{
// To-Do: code to Get Employee Details
}

public void SaveChanges()
{
// To-Do: code to Save Changes
}
}

Step 3: Create a controller class that depends on the IEmployeesRepository interface as shown below. In this code, the EmployeeController class constructor needs an implementation of the IEmployeesRepository interface as a parameter which will be injected at runtime which makes the controller loosely coupled to any class that implements the IEmployeesRepository interface.


public class EmployeeController : Controller
{
IEmployeesRepository employeesRepository;
public EmployeeController(IEmployeesRepository objEmployeesRepository)
{
employeesRepository = objEmployeesRepository;
}

public ActionResult UpdateEmployeeName(string oldName, string newName)
{
Employee employee = employeesRepository.GetEmployeeByName(oldName);
employee.EmpName = newName;
employeesRepository.SaveChanges();
//render Emp view or any other view

return View();
}
}


About Dependency Injection Container
In the above code, we have injected the dependencies into the constructor of our class at runtime. Dependency Injection Container is used to instantiate the concrete implementation of interfaces without creating dependencies somewhere else in our application.
dependency injection container is a component that acts like a broker between the dependencies that a class like UpdateDataService demands and the concrete implementation of the those dependencies such as EmailService.

To implement this IoC concept we have to register the interfaces or abstract types that our application uses with the DIcontainer, and tell it which concrete classes should be instantiated to satisfy dependencies.

In our case, We have to register the IEmailService interface with the container and specify that the object of EmailService should be created whenever an implementation of IEmailService is required. So when we need an IEmailService to create an instance of UpdateDataService , we go to the DI container and it gives an implementation of the class we registered as the default concrete implementation of the IEmailService interface which is EmailService .


Article by Vaishali Jain
Miss. Jain Microsoft Certified Technology Specialist in .Net(Windows and Web Based application development)

Follow Vaishali Jain or read 127 articles authored by Vaishali Jain

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: