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, 7:19 PM
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, 8:32 AM
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, 10:16 PM
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 10, 2018, 12:33 AM
Very nice and short example Yogesh i like it thank you for sharing knowledge.
Deepak ChauhanPosted May 25, 2018, 11:23 AM
Can u easy and short example of DI?
Sanju C KPosted Dec 19, 2017, 8:04 AM
Why do we need dependency injection? Without Registering we can achieve it with simple Interface implementation
chilumula vishnuPosted Nov 2, 2017, 10:02 AM
Good Example Yogesh Baipai
Asfend YarPosted Jan 26, 2017, 12:39 PM
Yeah Make sense but it's a short article for IOC and Dependency ...
Atul PrajapatiPosted May 31, 2016, 3:13 AM
Nice Article Yogesh
Yogesh BajpaiPosted Jan 31, 2016, 7:31 AM
Thanks Anupam
Anupam SinghPosted Jan 31, 2016, 7:28 AM
welcome back, nice share.
Muhammad Aqib ShehzadPosted Jan 25, 2016, 5:47 AM
good work dear
Mohammed IbrahimPosted Jan 25, 2016, 4:33 AM
nice