ASP.NET Core Dependency Injection

ASP.NET Core Dependency Injection with Example

In this article, I am going to discuss the ASP.NET Core Dependency Injection with an example. Please read our previous article before proceeding to this article where we discussed Models in ASP.NET Core MVC application. The Dependency Injection Design Pattern is one of the most used design Pattern in real-time application. But the good thing is that ASP.NET Core Provides inbuilt support for Dependency Injection. As part of this article, we are going to discuss the following pointers in details.

  1. Understanding the need for ASP.NET Core Dependency Injection
  2. What is Dependency Injection?
  3. How to register a Service with ASP.NET Core Dependency Injection Container?
  4. What are the different methods ASP.NET Core Provides to register a service with Dependency Injection Contains?
  5. Understanding the AddSingleton, AddScoped and AddTransient Methods
  6. What are the advantages of using Dependency Injection?
Understanding the need for ASP.NET Core Dependency Injection

Let us understand the need for ASP.NET Core Dependency Injection with an example. In our previous article, we have created the following classes within the Models folder.

Student.cs: This is our model class which is going to store the student data.

Student Model

IStudentRepository.cs: This is our student service interface. Here we need to declare the methods. As of now, we have only one method which will retrieve the student details based on student id.

IStudentRepository interface

TestStudentRepository.cs: This is the implementation class of our IStudentRepository service interface. Here we implement the GetStudentById method.

TestStudentRepository class

Startup.cs:

This is the class file where we need to register the required MVC services to dependency injection container and configuring the MVC middleware to the request processing pipeline.

Registering MVC Services and Middleware

HomeController.cs:

This is our MVC controller.

Controller

As shown in the above example, in order to get student data, the HomeController class depends on TestStudentRepository class. Here within the HomeController class, we create an instance of TestStudentRepository class and then invoke the GetStudentById() method. This is tight coupling because the HomeController class is now tightly coupled with the TestStudentRepository class.

Tomorrow if the implementation class of IStudentRepository is changed then we need to change the code in HomeController class as they both are tightly coupled. We can overcome this problem by implementing dependency injection design pattern.

What is Dependency Injection?

The Dependency Injection a process of injecting the object of a class into a class which depends on it. The Dependency Injection is the most commonly used design pattern nowadays to remove the dependencies between the objects. So, the Dependency Injection design pattern allows us to develop loosely coupled software components.

Let us discuss the step by step procedure to implement dependency injection in ASP.NET Core MVC application.

Modifying the HomeController:

First, modify the HomeController as shown below to use dependency injection.

using FirstCoreMVCApplication.Models;
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        //Create a reference variable of IStudentRepository
        private readonly IStudentRepository _repository = null;

        //Initialize the variable through constructor
        public HomeController(IStudentRepository repository)
        {
            _repository = repository;
        }

        public JsonResult GetStudentDetails(int Id)
        {
            //Use the _repository to call the GetStudentById method 
            Student studentDetails = _repository.GetStudentById(Id);
            return Json(studentDetails);
        }
    }
}
Code Explanation:

Here within the HomeController, instead of creating an instance of an implementation of IStudentRepository, we are injecting an instance of IStudentRepository through the constructor of HomeController class. As we are injecting the dependency object through a constructor, it is called as constructor dependency injection.

We created the variable as read-only which will ensure that once we injected the dependency object then that value can never be changed.

At this point, run the application and navigate to the /Home/GetStudentDetails/102 URL. You will get the following error.

ASP.NET Core Dependency Injection Error

We get the above error because the ASP.NET dependency injection container does not identify which class instance to provide if someone requests an object which implements the IStudentRepository.

In real-time, the IStudentRepository may have many implementation classes. As of now, we have only one implementation class of IStudentRepository i.e. TestStudentRepository. In a later article, we will discuss providing another implementation of IStudentRepository which will retrieve the student data from a database.

So, in order to overcome the above InvalidOperationException error, let’s register the TestStudentRepository class with the ASP.NET Core dependency injection container.

How to register a Service with ASP.NET Core Dependency Injection Container?

We need to register a service with ASP.NET Core Dependency Injection Container within the ConfigureServices() method of the Startup class.

Before we can discuss how to register a service with the Dependency Injection Container, it is important to understand the lifetime of service. When a class receives the dependency object through dependency injection, then whether the instance it receives is unique to that instance of the class or not depends on the lifetime of the service. Setting the lifetime of the dependency object determines how many times the dependency object need to be created.

What are the different methods ASP.NET Core Provides to register a service with Dependency Injection Contains?

The ASP.NET core provides 3 methods to register a service with the ASP.NET Core Dependency Injection container. The method that we use to register a service will determine the lifetime of that service.

  1. AddSingleton
  2. AddScoped
  3. AddTransient
AddSingleton():

When we use the AddSingleton() method to register a service, then it will create a singleton service. It means a single instance of that service is created and that singleton instance is shared among all the components of the application that require it. That singleton service is created when we requested for the first time.

AddScoped():

Scoped means instance per request. When we use the AddScoped() method to register a service, then it will create a Scoped service. It means, an instance of the service is created once per each HTTP request and uses that instance in other calls of the same request.

AddTransient():

When we use the AddTransient() method to register a service, then it will create a Transient service. It means a new instance of the specified service is created each time when it is requested and they are never shared.

Note: In the real-time applications, you need to register the components such as application-wide configuration as Singleton. The Database access classes like Entity Framework contexts are recommended to be registered as Scoped so that the connection can be re-used. If you want to run anything in parallel then it is better to register the component as Transient.

In this article, we are going to use the AddSingleton() method to register the component. In our upcoming articles, we will discuss the rest two methods.

Registering the TestStudentRepository with ASP.NET Core Dependency Injection 

Here we need to call the AddSingleton() method on the services instance within the ConfigureServices() method of the Startup class as shown below.

Registering a Service with ASP.NET Core Dependency Injection Container

With the above changes, now run the application and navigate to Home/GetStudentDetails/102 URL and you will see the output as expected.

What are the advantages of using ASP.NET Core Dependency Injection?

The ASP.NET Core Dependency Injection allows us to develop loosely coupled software components. Using the ASP.NET Core Dependency Injection, it is very easy to swap with a different implementation of a component.

In the next article, I am going to discuss the Controllers in ASP.NET Core MVC application. Here, in this article, I try to explain the ASP.NET Core Dependency Injection with an example. I hope this article will help you to understand the concept of Dependency Injection in ASP.NET Core Application. 

1 thought on “ASP.NET Core Dependency Injection”

Leave a Reply

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