直接上代码吧
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IOperationScoped, Operation>();
}
private readonly RequestDelegate _next;
private readonly IOperationScoped _scopedOperation;
public ServiceLifetimesMiddleware(RequestDelegate next,
IOperationScoped scopedOperation)
{
_next = next;
_scopedOperation = scopedOperation;
}
public async Task Invoke(HttpContext context)
{
await context.Response.WriteAsync($"Scoped:{_scopedOperation.OperationId}\r\n");
}
在中间件中报错:System.InvalidOperationException: Cannot resolve scoped service 'IOperationScoped' from root provider.
为什么在 mvc 下可以使用, mvc不也是个中间件吗?
将 IOperationScoped scopedOperation 写到 Invoke(HttpContext context) 参数里面