Dependency Injection Using Microsoft Unity

While developing software we follow specific Design Patterns. These design patterns have several uses; they are mainly used by developers to write better code, and to create applications that are more efficient and easier to test, debug, maintain, decouple, and extend. Currently we are mainly using the S.O.L.I.D design pattern.

S.O.L.I.D is an acronym for the first five object-oriented design (OOD) principles by Robert C. Martin, popularly known as Uncle Bob. These principles, when combined together, make it easy for a programmer to develop software that are easy to maintain and extend.

The name S.O.L.I.D is very interesting, When I heard this name I found it to be very funny. Actually at that time I did not understand what is the importance. Each letter in S.O.L.I.D represent a principle which is very important for software development. Here is what exactly the principle means: 
  • SSingle-responsibility principle
  • O – Open-closed principle
  • L – Liskov substitution principle
  • I – Interface segregation principle
  • D – Dependency Inversion Principle 

In this article I am going to describe an important principle, that is the last one: Dependency Inversion.

When I was new to this topic I was searching Google for the accurate definition of this principle. I got several definitions but I found one from Wikipedia that is appropriate for this concept:

In object-oriented programming, the dependency inversion principle refers to a specific form of decoupling software modules.

There are two main concepts of the Dependency Inversion Principle and these are:

1. The Dependency Inversion Principle (DIP) states that high-level modules/classes should not depend upon low-level modules/classes. Both should depend upon abstractions.

2. Abstractions should not depend upon details. Details should depend upon abstractions.

Dependency injection is a technique to develop software in an independent way. Independent in the sensethe  no module will depend on another module in the software development.

Sothe dependency injection technique will inject all dependencies of lower modules and provide these dependency to the higher module without direct contact.

High-level modules/classes implement business rules or logic in an application. Low-level modules/classes deal with different operations; in other words, they may deal with writing information to databases or passing messages to the operating system or services, etc.

The fully dependent application will look something like this. All modules are tightly coupled with each other. 

Direct Dependent image

As per Dependency Inversion Principle there is someone between them to decouple these models.

independent image

Here now I will explain how we can implement this in our MVC  Project.

Dependency Injection using Microsoft Unity 

1. Create a new project.

 

2. Select the template MVC.

 

3. Now create a class Employee.cs and an Interface Iemployee.cs as shown in the project.

Solution explorer

4. Now go to Manage NuGet Package and install Unity.Mvc3.

 

After installing we will get two references in our project as follows.

 

After installing unity we get these two things in the references.

5. Now you will check in the App_start folder you will get a new class file of unity or you can get a file named Bootstrapper.cs.
 
I have here the Bootstrapper.cs and registering the following interface there as follows.
  1. private static IUnityContainer BuildUnityContainer()    
  2. {    
  3.     var container = new UnityContainer();    
  4.     container.RegisterType<IEmployee,Employee>();    
  5.   
  6.     // register all your components with the container here    
  7.     // it is NOT necessary to register your controllers    
  8.         
  9.     // e.g. container.RegisterType<ITestService, TestService>();                
  10.   
  11.     return container;    
  12. }   
In the Unity Container I am registering the type Iemployee with Employee class.
 
6. Go to global.ascx and register the bootstrapper as follows.
  1. public class MvcApplication : System.Web.HttpApplication    
  2.     
  3.    protected void Application_Start()    
  4.    {    
  5.        AreaRegistration.RegisterAllAreas();    
  6.        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);    
  7.        RouteConfig.RegisterRoutes(RouteTable.Routes);    
  8.        BundleConfig.RegisterBundles(BundleTable.Bundles);    
  9.   
  10.        Bootstrapper.Initialise();    
  11.    }   
7. Now we are writing one abstract method in the interface and implementing the interface in the class as follows. Here I have written a simple method. 
  1. public interface IEmployee  
  2. {  
  3.    string savedata();  
  4. }  
8. Now in the Employee class I am implementing the interface and defining the savedata method.
  1. public class Employee:IEmployee    
  2. {    
  3.   
  4.     public string savedata()    
  5.     {    
  6.         return "Data Saved...";    
  7.     }    
  8. }   
Now almost all the work has been finished. Now we will see how to decouple these things.
 
NOTE: When we are creating an object of a class and calling that class method by its object from another class, then we will say that the two classes are tightly coupled or dependent on each other.

So our aim here is to decouple each class, so here without creating any instance, I will call another class method. Let's see how.
 
9. In the Home Controller just add the following code:
  1. public class HomeController : Controller    
  2. {    
  3.     IEmployee iemployee;    
  4.     public HomeController(IEmployee _iemployee)    
  5.     {    
  6.         iemployee = _iemployee;    
  7.   
  8.     }   
So here I am doing a Constructor Injection by creating a constructor and passing the dependency in the constructor.

Now when you try to access the employee class method you can do as follows in another action method.

 
Here is the code of the screenshot.
  1. public class HomeController : Controller    
  2. {    
  3.     IEmployee iemployee;    
  4.     public HomeController(IEmployee _iemployee)    
  5.     {    
  6.         iemployee = _iemployee;    
  7.   
  8.     }    
  9.     public ActionResult Index()    
  10.     {    
  11.        string result= iemployee.savedata();    
  12.        return Content(result);    
  13.     }    
Now just save the program and run. It will produce the following output:
 
Run
So in this we can see how to implement dependency injection using Unity.
 
Ream more articles on Design Patterns:


Similar Articles