Open In App

Creation of Custom Middleware using IMiddleware Interface in ASP.NET Core

Last Updated : 19 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The IMiddleware Interface in ASP.NET Core is a contract for creating a custom middleware that can be added to the application's existing pipeline. This interface was introduced in ASP.NET Core to provide an alternative way to create middleware components, apart from the traditional RequestDelegate-based middleware. The main difference is that IMiddleware supports dependency injection via the constructor more naturally, making it easier to manage and test i.e. unlike traditional middleware, which is generally registered using UseMiddleware<T>() extension, IMiddleware implementation can be registered and resolved directly through the DI container.

Moreover, middleware implemented using IMiddleware are transient by nature. A new instance of the middleware is created per request, which can be useful for particular scenarios where you need a fresh state and specific scoped services.

Now let's see how to use it:

  1. Middleware Class Implementing IMiddleware: Create a class implementing IMiddleware and define the InvokeAsync function to specify the custom middleware's behaviour.
  2. Register the Middleware in the DI Container: Register your middleware class in Startup.cs class as a transient service in the ConfigureService method.
  3. Use the Middleware in the Pipeline: In Startup.cs class, inside Configure method write app.UseMiddleware<CustomMiddleware>().
C#
public class Custom_Middleware: IMiddleware
{
  private readonly IMyService _myService;
  public Custom_Middleware(IMyService myService)
  {
  	_myService = myService;
  }
  public async Task InvokeAsync(HttpContext context, RequestDelegate next)
  {
  	//your custom logic here
    await next(context);
  }
}

//In Startup.cs inside ConfigureService method
services.AddTransient<Custom_Middleware>();

//In Startup.cs inside Configure method
app.UseMiddleware<Custom_Middleware>();

Conclusion

The IMiddleware interface in ASP.NET Core provides a more explicitly DI-friendly way to create custom middleware components. It simplifies dependency injection via constructor injection and allows for better management and testing of middleware. Its transient nature also ensures that a new instance of middleware is created per request, which is useful for handling fresh state and scoped services.


Next Article
Article Tags :

Similar Reads