How to do di in asp net core middleware


ASP.NET is a popular programming language used for building web . One common task in ASP.NET is injection (DI), which allows for the management and injection of dependencies into or components. In this article, we will explore how to implement DI in ASP.NET Core middleware.

What is Dependency Injection?

Dependency Injection is a pattern that allows for the separation of concerns and promotes loose coupling between components. It involves injecting dependencies into a rather than them within the class itself. This makes the code more modular, testable, and maintainable.

Implementing DI in ASP.NET Core Middleware

In ASP.NET Core, middleware is used to handle requests and responses. It sits between the web and the application, allowing for the processing of incoming requests and the generation of outgoing responses. To implement DI in middleware, we need to follow a few steps.

Step 1: Define the Dependency

The first step is to define the dependency that we want to inject into the middleware. This can be done by creating an interface or a class that represents the dependency. Let's take an example where we want to inject a logger into our middleware:

public interface ILogger
    void Log(string message);

public class Logger : ILogger
    public void Log(string message)
        // Implementation of logging logic

Step 2: Register the Dependency

Next, we need to register the dependency in the ASP.NET Core dependency injection . This can be done in the ConfigureServices method of the Startup class. We can use the AddScoped method to register the dependency as a scoped service:

public void ConfigureServices(IServiceCollection services)

Step 3: Inject the Dependency into Middleware

Finally, we can inject the dependency into our middleware by adding it as a parameter in the middleware constructor. ASP.NET Core will automatically resolve the dependency and provide an of it when the middleware is instantiated:

public class MyMiddleware
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public MyMiddleware(RequestDelegate next, ILogger logger)
        _next = next;
        _logger = logger;

    public async Task Invoke(HttpContext context)
        // Middleware logic here
        _logger.Log("Middleware invoked");

        await _next(context);


Dependency Injection is a powerful technique that can greatly improve the modularity and maintainability of ASP.NET Core middleware. By the steps outlined in this article, you can easily implement DI in your middleware and inject dependencies as needed. This promotes code reusability, testability, and overall better software design.

Rate this post

Leave a Reply

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

Table of Contents