为什么无法在自定义中间件的构造函数中解析 DbContext?

Why cannot resolve DbContext in constructor of custom middleware?

我有自定义中间件。我尝试了构造函数注入来注入我的 DbContext。但它不起作用。以下不起作用并给出 InvalidOperationException:无法从根提供程序解析作用域服务 'MyDbContext';

private MyDbContext _context;    
public RequestResponseMiddleware(RequestDelegate next, MyDbContext context)
{
    _next = next;
    _context = context;
} 

但是当我在 InvokeAsync 方法中将它用作参数时它起作用了。以下作品

public Task InvokeAsync(HttpContext context, MyDbContext  _context)
{

}

有谁知道原因吗?

DbContext 通常注册为作用域服务。

When using a scoped service in a middleware, inject the service into the Invoke or InvokeAsync method. Don't inject via constructor injection because it forces the service to behave like a singleton. For more information, see ASP.NET Core Middleware.

强调我的

引用Dependency injection in ASP.NET Core: Scoped Service lifetime