You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加Scoped服务抛出异常:无法从根提供程序解析Scoped服务

问题分析与解决方案

错误原因

ASP.NET Core中中间件默认是单例生命周期,而你注入的IMyLogger是Scoped生命周期(每个请求创建实例)。单例服务由根服务提供者管理,根提供者无法解析Scoped服务——因为Scoped服务的生命周期绑定到请求,根容器不存在请求上下文,因此抛出Cannot resolve scoped service from root provider错误。

当你把IMyLogger改为Singleton时,服务生命周期和中间件一致(都是应用级别),根容器可以正常解析,所以不会报错。

解决方案

方案1:在Invoke方法中注入Scoped服务(推荐)

修改中间件,不在构造函数注入Scoped服务,而是在Invoke方法中通过依赖注入获取,因为Invoke方法的参数会在请求上下文里解析:

public class LogMiddleware
{
    private readonly RequestDelegate _next;

    public LogMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task Invoke(HttpContext httpContext, IMyLogger logger)
    {
        logger.Info("In Logger MiddleWare");
        return _next(httpContext);
    }
}

或者手动从HttpContext.RequestServices中获取:

public Task Invoke(HttpContext httpContext)
{
    var logger = httpContext.RequestServices.GetRequiredService<IMyLogger>();
    logger.Info("In Logger MiddleWare");
    return _next(httpContext);
}

方案2:将中间件注册为Scoped(不推荐)

如果必须在构造函数注入Scoped服务,可以将中间件注册为Scoped生命周期,但这种方式会降低性能,因为每个请求都会创建中间件实例:

// Program.cs中修改中间件注册代码
app.UseMiddleware<LogMiddleware>(ServiceLifetime.Scoped);

内容的提问来源于stack exchange,提问作者Tal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 16:22:43