Working With Dependency Injection in MVC Application

Dheeraj Kumar Gunti

Reading Time : ( words)

In Software programming, building an effective and efficient application is the primary role and for that to acheive the main key role is to have a good architecture in place. With Good Architecture we can achieve the key objective.

In this article we will see how to use dependency injection pattern using Unity on an MVC application. This article is intended to give a brief idea how to use, and real example will differ based on the architecture developer follows.

First lets see what is dependency injection in other words we call Inversion of Control (IOC), In Simple words dependency injection is a process where high level modules won't depend on low level modules . The main intent of using Dependency injection is to make application loosely coupled where application won't depend on concrete class rather it depends on its abstraction. Dependency injection is a way to remove hard-coded dependencies among objects.

Dependency injection allows a program design to follow the dependency inversion principle. There are four types where we can use dependency injection -

  1. Constructor
  2. Property
  3. Interface
  4. Service

Constructor Dependency Injection - This is the most commonly used Dependency Pattern in Object Oriented Programming. The Constructor Injection uses a parameter to inject dependencies so there is normally one parameterized constructor always. So in this constructor dependency, the object has no default constructor and you need to pass specified values at the time of creation to initiate the object.

Property or Setter Injection - Injecting using default get and set properties.

Using Unity we will be resolving the dependency and make our application to understand all the dependencies.

Lets create a small example using Dependency Injection and Unity Container.

Create a simple MVC application and have a simple model.

Create an interface and implement that in a class.

Using NuGet package Manager Install Unity.MVC4

Install-Package Unity.Mvc4

Once the installation is done package will install one static class which is Bootstrapper, which actually has certain methods and process to resolve the dependencies. With respect to our application we need to register our components in this class.

Specify the below statement in Global.asax - Application_Start.

Create a controller and use Empty template.

Add an empty constructor and specify the IEmployee object.

In the index action we are returning all the employees using employee.GetAllEmployees() method.

Dependency Injection can be extended a lot based on the architecture that we design.

Advantages of DI:

  • Reduces class coupling
  • Increases code reusability
  • Improves code maintainability
  • Improves application testing

Enjoy Coding.........