Dependency Injection (DI) in MVC

Use for tightly coupled to Loosely Coupled.

DI implantation using “Inversion Of Control (IoC)” .

What Is Inversion Of Control (IoC) ?

  • Object do not create other object which they rely to do their work but they get the object from outside source.

For Example:

Without Inversion of Control.

public class TextEditor {

    private SpellChecker checker;

    public TextEditor() {
        this.checker = new SpellChecker();
  • What we’ve done here creates a dependency between the TextEditor and the SpellChecker.

With Inversion of Control.

  • In Inversion of Control scenario we would instead do something like this
public class TextEditor {

    private IocSpellChecker checker;

    public TextEditor(IocSpellChecker checker) {
        this.checker = checker;
  • You have inverted control by handing the responsibility of instantiating the spell checker from the TextEditor class to the caller.
  • In MVC, There is no Inbuilt feature for Dependency Injection. So we have to achieve through different container like Unity, Ninject and  Autofac etc.
  • (Note: In .Net core there is Inbuilt feature for dependency Injection so no need to add any container.)
  • In this tutorial, we are using Unity Container for achieve Dependency Injection.

Step 1: Add a new Asp.Net Mvc Project.

Step 2: Now, Install “Unity.Mvc5” Container using Nuget package Manager.

  • After install successfully, two file references added to our project and a UnityConfig.cs class file in App-Start file.

Step 3

  • Add Interface IEmployeeRepository inside interface folder.

  • Now Add Repository Which have Data access Code which inherit to Interface as per below SS.

Step 4: Now register the repository inside UnityConfig.cs file.

Step 5: Now inject the dependency in Controller.

Step 6: Add View for the same.

Finally, run the project,

  • In Future, we need to change the repository that time simply change the repository in UnityConfig.cs File like below

  • The main purpose is to no need to change in every controller, just simply change on container that’s means totally loosely coupled.
  • After Run the Project,

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories