Dependency Injection in C#

Dependency Injection in C#
Dependency Injection in C#

Introduction

In the previous article, you have learned about how to map the database data to the model and display it in a view with Dapper Micro ORM in the MVC application.

In this article, you will learn about what is dependency injection, how to use it in MVC application the benefits of that.

This article will be helpful to beginners and students who are learning MVC. 

Pre-Requisites

  • You need to create an ASP.NET MVC Project (You can refer our article to create a new project), Or you can add this to the existing project.

What is Dependency Injection

The Dependency Injection is a particular implementation of Inversion of Control that means that objects do not create other objects on which they are dependent to do their work. Instead, they get the objects that they need from an outside source.

DI is like passing a dependency object to other objects. Dependency Injection can be done via the constructor.

Example: Suppose you have a class called PlayGame. It required two services 1. AddScore (To add a score in the database ) 2. AddScore(To add a score in the document), So by applying abstraction by interface IGameRequirements to these services. This way, you can change the implementation of the IGameRequirements interface at any time (and for how many times you want) without changing the client class code. You can see the code below for a better idea.

public class PlayGame {  
    private readonly IGameRequirements gameReq;  
    public PlayGame(IGameRequirements gameReq) {  
        this.gameReq = gameReq;  
    }  
    public void Add(string Score) {  
        gameReq.AddScore("GameScore", Score);  
    }  
}  
public interface IGameRequirements {  
    void AddScore(string Table, string Value);  
}  
public class GameDatabase: IGameRequirements {  
    public void AddScore(string Table, string Value) {  
        //Logic to add score in GameScore in sql table  
    }  
}  
public class GameDocument: IGameRequirements {  
    public void AddScore(string Table, string Value) {  
        //Logic to add score in  Document  
    }  
} 

There are mainly three types of classes in the Dependency Injection pattern.

  1. Dependent Class: This is a class that depends on the Dependency Class.
  2. Dependency Class: This provides service to the Dependent Class
  3. Injector Class: This class injects the Dependency class objects to the dependent class.

Types Of Dependency Injection:

  • Constructor Injection: In the constructor injection, the injector supplies dependency through the client class constructor.
  • Property Injection: In the property injection, the injector supplies the dependency through a public property of the client class.
  • Method Injection: In this injection, the dependent class implements an interface that declares the method(s) to supply the dependency and the injector uses this interface to supply the dependency to the client class.

Need Of Dependency Injection

To Achieve the code re-usability and to write well maintainable and testable code DI is very important.

Dependency Injection is useful to write loosely coupled code. Lets see the below example to get idea about how we can write loosely coupled code.

Loosely Couple Code means a class is not dependent on the other group classes, It can be tested separately , a class that is having single responsibility.

Loosely Couple code can be achieved by using an interface. Classes can communicate through the interface by just implementing it.

Benefits Of Dependency Injection

There are few benefits of Dependency Injection in Mvc as listed below.

  • DI reduced the container or the service of unnecessary dependency. If the dependencies are less then the changes that you have to make is also reduced
  • Di increases the re-usability of code because it reduces dependency.

How to achieve DI in C#

There are So many tools available to achieve Dependency Injection in MVC, i.e. Unity, Autofac, Ninject, StructureMap, etc…

In this article, we will see how to achieve Dependency Injection with the help of Structure Map dependency resolver.

Step 1: Right-click on the project and add a nugget package named “StrucutreMap.MVC5” as shown below.

Step 2: Create a Class a and Interface that contains the appropriate methods

A method that id declared in the interface will be defined in the class where the interface is inherited,

So, here I have created a class file(service file) called EmployeeService.cs. this file contains a class called EmployeeService and the interface IEmployeeService that inherits to class EmployeeService. The method GetEmployeeModels() is declared in the interface and it is defined in the class where IEmployeeService interface is inherited.

namespace EmployeePanel.Service
{
   public interface IEmployeeService
    {
        IEnumerable GetEmployeeModels();


    }
    public class EmployeeService: IEmployeeService
    {
        public IEnumerable GetEmployeeModels()
        {
            EmployeeEntities employeeEntities = new EmployeeEntities();
            return employeeEntities.Users.ToList();
        }
    }
}

Step 3:

Configure the service class (dependency class OR Container) that you have created in the DefaultRegistry.cs  class, each and every dependency class that you create needs to be registered in this repository

There are two ways of registering your service or container, You can configure by explicit configuration or by the auto configurations, we will do by explicit configuration, because we have only one service to configure, If you have so many containers of service to configure than explicit configuration become more frustrating to do, So there is a way called autoconfiguration mechanism so that, Whenever you add an additional interface, it’s automatically picked up by the scanner scan.WithDefaultConventions();

In the below code i have done explicit configuration.

using EmployeePanel.Service;
using StructureMap.Configuration.DSL;
using StructureMap.Graph;
namespace EmployeePanel.DependencyResolution {
    public class DefaultRegistry : Registry {
        #region Constructors and Destructors
        public DefaultRegistry() {
            Scan(
                scan => {
                    scan.TheCallingAssembly();
                    scan.WithDefaultConventions();
                    scan.With(new ControllerConvention());
                });
            For().Use();
        }
        #endregion
    }
}

Step 4: Create a new controller as below and use the Dependency Injection pattern in the constructor as given in the below code.

Home.cs

  public class HomeController : Controller
    {
        private readonly IEmployeeService employeeService;
        public HomeController(IEmployeeService _employeeService)
        {
            employeeService = _employeeService;
        }
        public ActionResult Index()
        {
            var employees = employeeService.GetEmployeeModels();
            return View(employees);
        }
    }

In the view of the index method, we will display the employee details by data we get using DI, as shown in below code

Index.cshtml

@model IEnumerable

@{
    ViewBag.Title = "Index";
}

Employee Details

@foreach (var item in Model) { }
First Name Last Name Email Phone Number
@item.FirstName @item.LastName @item.Email @item.PhoneNumber

So when you run the code you will get a list of employee details as below given image.

I hope this article will help you to learn about Dependency Injection and how to use it in MVC application. we will be happy to help you if you have any issues or queries. Comment your suggestions and issues and we will try to resolve it.

What is your reaction?

0
Excited
0
Happy
0
In Love
0
Not Sure
0
Silly

You may also like

Comments are closed.

More in MVC