Add support for IMiddlewareFactory and IMiddleware #754
Description
The IMiddlewareFactory
is a new extensibility point for middleware activation that would be registered with the application's container. The default IMiddlewareFactory
should be registered as a scoped service, and (maybe) only resolve middlewareType
s that are already registered in the container.
Hosting will probably need to add the default IMiddlewareFactory
to the container, but the implementation can stay in HttpAbstractions.
namespace Microsoft.AspNetCore.Http
{
/// <summary>
/// Provides methods to create middlware.
/// </summary>
public interface IMiddlewareFactory
{
/// <summary>
/// Creates a middleware instance for each request.
/// </summary>
/// <param name="middlewareType">The concrete <see cref="Type"/> of the <see cref="IMiddleware"/>.</param>
/// <returns>The <see cref="IMiddleware"/> instance.</returns>
IMiddleware Create(Type middlewareType);
/// <summary>
/// Releases a <see cref="IMiddleware"/> instance at the end of each request.
/// </summary>
/// <param name="middleware">The <see cref="IMiddleware"/> instance to release.</param>
void Release(IMiddleware middleware);
}
/// <summary>
/// Defines middleware that can be added to the application's request pipeline.
/// </summary>
public interface IMiddleware
{
/// <summary>
/// Request handling method.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
/// <param name="next">The delegate representing the remaining middleware in the request pipeline.</param>
/// <returns>A <see cref="Task"/> that represents the execution of this middleware.</returns>
Task Invoke(HttpContext context, RequestDelegate next);
}
}
The typed UseMiddleware
extension methods would check if the registered type implements the new IMiddleware
interface. If it does, it will automatically decide to use the IMiddlewareFactory
to resolve the IMiddleware
instead of using the existing middleware activation logic. This will likely be implemented by registering a Func<RequestDelegate, RequestDelegate>
that resolves the IMiddlewareFactory
from HttpContext.RequestServices
.
The existing middleware activation logic will remain for convention-based middleware to preserve backwards compatibility.