AspNetCore.Docs/aspnetcore/fundamentals/middleware/extensibility.md

4.5 KiB

title author description ms.author manager ms.custom ms.date ms.topic ms.technology ms.prod uid
Factory-based middleware activation in ASP.NET Core guardrex Learn how to use strongly-typed middleware with a factory-based activation implementation in ASP.NET Core. riande wpickett mvc 01/29/2018 article aspnet asp.net-core fundamentals/middleware/extensibility

Factory-based middleware activation in ASP.NET Core

By Luke Latham

IMiddlewareFactory/IMiddleware is an extensibility point for middleware activation.

UseMiddleware extension methods check if a middleware's registered type implements IMiddleware. If it does, the IMiddlewareFactory instance registered in the container is used to resolve the IMiddleware implementation instead of using the convention-based middleware activation logic. The middleware is registered as a scoped or transient service in the app's service container.

Benefits:

  • Activation per request (injection of scoped services)
  • Strong typing of middleware

IMiddleware is activated per request, so scoped services can be injected into the middleware's constructor.

View or download sample code (how to download)

The sample app demonstrates middleware activated by:

The middleware implementations function identically and record the value provided by a query string parameter (key). The middlewares use an injected database context (a scoped service) to record the query string value in an in-memory database.

IMiddleware

IMiddleware defines middleware for the app's request pipeline. The InvokeAsync(HttpContext, RequestDelegate) method handles requests and returns a Task that represents the execution of the middleware.

Middleware activated by convention:

[!code-csharpMain]

Middleware activated by MiddlewareFactory:

[!code-csharpMain]

Extensions are created for the middlewares:

[!code-csharpMain]

It isn't possible to pass objects to the factory-activated middleware with UseMiddleware:

public static IApplicationBuilder UseIMiddlewareMiddleware(
    this IApplicationBuilder builder, bool option)
{
    // Passing 'option' as an argument throws a NotSupportedException at runtime.
    return builder.UseMiddleware<IMiddlewareMiddleware>(option);
}

The factory-activated middleware is added to the built-in container in Startup.cs:

[!code-csharpMain]

Both middlewares are registered in the request processing pipeline in Configure:

[!code-csharpMain]

IMiddlewareFactory

IMiddlewareFactory provides methods to create middleware. The middleware factory implementation is registered in the container as a scoped service.

The default IMiddlewareFactory implementation, MiddlewareFactory, is found in the Microsoft.AspNetCore.Http package (reference source).

Additional resources