- 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.
DI is a software design pattern that allow us to develop loosely coupled code.
Way of achieve Dependency Injection in MVC
Create an MVC Application,
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;
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";
After this register IOCConfig in Global.asax,
Step 6: Finally, use it in your MVC Controller,