Dependency Injection in MVC

Agenda
  1. What is Inversion of Control?
  2. What is Dependency Injection?
  3. Way of achieving Dependency Injection in MVC.
Inversion of Control (IoC)

Inversion of Control (IoC) refers to a programming style where a framework controls the program flow with the help of Dependency Injection.

Dependency Injection

DI is a software design pattern that allow us to develop loosely coupled code.

Way of achieve Dependency Injection in MVC

Step 1: Create an MVC Application,

Application
Step 2:

Right click on project and from context menu click on Manage Nuget Packages and search for Unity.mvc5. Click to install Unity.mvc5 package in ASP.NET MVC application.

package

Once Unity.mvc5 is installed then the following references will be added,

references
 
Step 3: Add IOCConfig.cs under App_Start folder as in the following screenshot;

screen

Step 4: Add service folder and then create an interface as in the following screenshot:

screen
  1. public interface ICompanyService  
  2. {  
  3.     string GetCompany();  
  4. }  
  5.   
  6. After this,  
  7.   
  8. public class CompanyService: ICompanyService  
  9. {  
  10.     public string GetCompany()  
  11.     {  
  12.         return "test Company";  
  13.     }  
  14. }  
  15. }  
  16. }  
Step 5: After this register IOCConfig in Global.asax,

IOCConfig

Step 6:
Finally, use it in your MVC Controller,

Controller


Similar Articles