Agenda
- What is Inversion of Control?
- What is Dependency Injection?
- 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,

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.

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

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

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

- public interface ICompanyService
- {
- string GetCompany();
- }
- After this,
- public class CompanyService: ICompanyService
- {
- public string GetCompany()
- {
- return "test Company";
- }
- }
- }
- }
Step 5: After this register IOCConfig in Global.asax,


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



Ajith V SPosted Jan 24, 2020, 2:19 PM EST
Thanks for the explanation. I have a doubt. If I need a different implementation of I company service during the runtime how could I inject? Might be a wrong scenario..
Adhi VenkateshPosted Sep 17, 2019, 4:32 AM EDT
Nice and legible to explain , this you would tried for db connection event its good , we can try this also as a base controller which is quite professional. thanks for your block.
Muhammad Ashikuzzaman AshikPosted Jan 2, 2019, 5:16 PM EST
Nice post. Worked for me. But in my reference directory I am seeing this Unity.Mvc5. Also seeing this "The current type, Microsoft.AspNet.Identity.IUserStore`1[AspMvc5MultiTenantProject.Models.ApplicationUser], is an interface and cannot be constructed. Are you missing a type mapping?" error in http://localhost/Account/Login . Now have a solution here https://stackoverflow.com/questions/24740619/
Arjun DhilodPosted Dec 9, 2018, 7:33 PM EST
Very nice and short example Yogesh i like it thank you for sharing knowledge.
Deepak ChauhanPosted May 25, 2018, 7:23 AM EDT
Can u easy and short example of DI?
Sanju C KPosted Dec 19, 2017, 3:04 AM EST
Why do we need dependency injection? Without Registering we can achieve it with simple Interface implementation
chilumula vishnuPosted Nov 2, 2017, 6:02 AM EDT
Good Example Yogesh Baipai
Asfend YarPosted Jan 26, 2017, 7:39 AM EST
Yeah Make sense but it's a short article for IOC and Dependency ...
Atul PrajapatiPosted May 30, 2016, 11:13 PM EDT
Nice Article Yogesh
Yogesh BajpaiPosted Jan 31, 2016, 2:31 AM EST
Thanks Anupam
Anupam SinghPosted Jan 31, 2016, 2:28 AM EST
welcome back, nice share.
Muhammad Aqib ShehzadPosted Jan 25, 2016, 12:47 AM EST
good work dear
Mohammed IbrahimPosted Jan 24, 2016, 11:33 PM EST
nice