![]() |
VOOZH | about |
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:
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.