ASP.NET Core 中基于工厂的中间件激活(推荐)
IMiddlewareFactory/IMiddleware 是中间件激活的扩展点,具有以下优势:
- 按客户端请求(作用域服务的注入)激活
- 让中间件强类型化
UseMiddleware 扩展方法检查中间件的已注册类型是否实现 IMiddleware。 如果是,则使用在容器中注册的 IMiddlewareFactory 实例来解析 IMiddleware 实现,而不使用基于约定的中间件激活逻辑。 中间件在应用的服务容器中注册为作用域或瞬态服务。
IMiddleware 按客户端请求(连接)激活,因此作用域服务可以注入到中间件的构造函数中。
IMiddleware
使用 MiddlewareFactory 激活的中间件:
public class FactoryActivatedMiddleware : IMiddleware { private readonly SampleDbContext _dbContext; public FactoryActivatedMiddleware(SampleDbContext dbContext) => _dbContext = dbContext; public async Task InvokeAsync(HttpContext context, RequestDelegate next) { var keyValue = context.Request.Query["key"]; if (!string.IsNullOrWhiteSpace(keyValue)) { _dbContext.Requests.Add(new Request("Factory", keyValue)); await _dbContext.SaveChangesAsync(); } await next(context); } }
为中间件创建扩展:
public static class MiddlewareExtensions { public static IApplicationBuilder UseFactoryActivatedMiddleware( this IApplicationBuilder app) => app.UseMiddleware<FactoryActivatedMiddleware>(); }
将以工厂激活的中间件添加到 Program.cs
的内置容器中:
var builder = WebApplication.CreateBuilder(args); builder.Services.AddDbContext<SampleDbContext> (options => options.UseInMemoryDatabase("SampleDb")); builder.Services.AddTransient<FactoryActivatedMiddleware>();
将中间件在 Program.cs
的请求处理管道中注册:
var app = builder.Build(); app.UseFactoryActivatedMiddleware();