• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Sunday, August 23, 2020

ASP.NET Core Dependency Injection

 Admin     August 23, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

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 Patterns in real-time applications. 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 the 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 the IStudentRepository is changed then we need to change the code in the 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 that 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 the 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 the 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 needs 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.

Summary:
I hope this post will be helpful to understand the concept of ASP.NET Core Dependency Injection
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape