Dependency Injection in MVC 3 Using Constructor Injection in Unity

First of all I’d like to wish you a Happy New Year 2014. A New Year with new aspirations and fresh thoughts. After a short interval I thought to write a new article on the grooming technology MVC.

For exploring MVC more, today I will share one of the interesting facts about Dependency Injection via constructor. There are many other ways to do the DI however I thought to explain how to implement this. Probably I’ll cover others in my future articles. Kindly visit the latest article that I wrote at the very start of this month.

Similarities and Dissimilarities Between MVC and Web Forms

I have seen many articles about Dependency Injection. And thought to write an article to inject dependency after initializing the DBContext object.

Object-oriented applications have a major component of design, "loose coupling".

Loose coupling means that objects should only have as many dependencies as is needed to do their job and the dependencies should be fewer. In addition to this, an object's dependencies should be on interfaces and not on "concrete" objects, a concrete object is any object created with the keyword "new".

The technique "Inversion of Control" (IOC) can be used for loose coupling. Kindly have a look at the following link to understand IOC.

S.O.L.I.D Principle Inversion of Control and Resolution With Dependency Injection

There are two primary approaches to implement DI: constructor injection and setter injection. I’ll be focusing on constructor injection.

Now the question is “if we don’t create an object using new then how would it call the required action to perform some operation (method)”. The answer is of course it would create an object using new but not in the same class and inject into another object (in other words constructor level) so that it could minimize the dependency within any class.

An Excerpt from MSDN

Dependency Injection (DI) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and set properties.

The Dependency Injection (DI) Design Pattern

At a high level, the goal of Dependency Injection is for a client class (for example a golfer) needs something that satisfies an interface (for example IClub). It doesn't care what the concrete type is (for example WoodClub, IronClub, WedgeClub orPutterClub), it wants someone else to handle that (for example a good caddy). The Dependency Resolver in ASP.NET MVC can allow you to register your dependency logic somewhere else (for example a container or a bag of clubs).

Dependency Injection

Dependency Injection Golf analogy

I’ll be using Unity 2.x to maintain the IOC in my solution. Kindly download the Unity 3 - April 2013

UnityQuickStarts.zip that is being used in this solution, though I’ll explain each step so that it can be understood better by everyone. I am always trying to keep my article more readable and understandable.

So let’s start with the implementation now. I’ve created a sample application in MVC3 having the structure given below along with the Unity DLLs marked with red.

mvc Application

Note

There is a folder named Services having an interface IEmployee and a class Employee that implements an IEmployee interface. We’ll inject the IEmployee interface object into our controller via constructor rather than creating an object of DBContext in the same class. Now the Employee class is responsible for creating an object of DBContext using the new keyword.

I’ve added the required reference to the Unity DLL. Kindly look at the depicted image below:

Reference Folder

There is a class named UnityDepandencyResolver to resolve the dependency also depicted in the following image.

Key Note

In MVC 4 whenever you will install Unity using the NuGet Manager it will auto-install in your solution with the name "BootStrapper.cs".

BootStrapper

We’re almost done but now certainly the question “how we’d inject the dependency in a respective controller” is relevant because it’s not magic.

The solution is: register your controller, interface and class in Global.asax and here is the code segment for that.

IUnityContainer container = new UnityContainer(); container.RegisterType<RegisterController>();

container.RegisterType<IEmployee, Employee>();

DependencyResolver.SetResolver(new UnityDepandencyResolver(container));

The preceding code segment registers the Controller, interface and class and resolves the dependency via the UnityDepandencyResolver class.

Now I am done with the coding part and run the application and see how things go to. Press F5.

First it goes into the Global.asax file to register the Controller, Interface and class, please see the image shown below:

Global File

Press F10 to proceed further.

It jumps into the UnityDepandencyResolver and verifies whether or not the serviceType has been registered. Please have a look at the image below:

serviceType

If it has been registered then now it moves into the Employee class to create and the object of the DBContext that we’ll be using in RegisterController with an interface.
 
RegisterController

After resolving the dependency it finally moves to the Register Controller class and injects the dependency into the constructor shown in the image below.

Constructor

Later it executes the Verify action method and responds with the result in the View as shown below.

The advantages of using the Dependency Injection pattern and Inversion of Control are the following:
  • Reduces class coupling
  • Increases code reusing
  • Improves code maintainability
  • Improves application testing

Disadvantages

  • Code complexity, classess and interface declaration
  • Debugging should be in depth

Up Next
    Ebook Download
    View all
    Learn
    View all