c# - Cannot resolve scoped service 'xx.IEnumerable`1[xx.IDbContextOptionsConfiguration`1[xx.ExampleDbContext]]...&#3

I recently upgraded my project from .NET 8 to .NET 9, and I encountered the following error when runnin

I recently upgraded my project from .NET 8 to .NET 9, and I encountered the following error when running my application:

Cannot resolve scoped service 'System.Collections.Generic.IEnumerable`1[Microsoft.EntityFrameworkCore.Infrastructure.IDbContextOptionsConfiguration`1[TestEFCore9Worker.Context.ExampleDbContext]]' from root provider.

Context: I'm using EF Core for database access. My ExampleDbContext is registered in the ServiceCollection using the following configuration in Program.cs:

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<Worker>();

builder.Services.AddDbContextFactory<ExampleDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DbConnectionString"));
});

builder.Services.AddDbContext<ExampleDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DbConnectionString"));
});

var host = builder.Build();
host.Run();

Below is the constructor of my ExampleDbContext. File ExampleDbContext.cs

public class ExampleDbContext : DbContext
{
    public ExampleDbContext(DbContextOptions options) : base(options)
    {
    }

    public required virtual DbSet<ExampleModel> Examples { get; set; }
}

In Worker.cs

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public Worker(ILogger<Worker> logger, IServiceScopeFactory serviceScopeFactory)
    {
        _logger = logger;
        _serviceScopeFactory = serviceScopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            }

            using (IServiceScope serviceScope = _serviceScopeFactory.CreateScope())
            {
                var dbContextFactory = serviceScope.ServiceProvider.GetRequiredService<IDbContextFactory<ExampleDbContext>>();
                using var dbContext = dbContextFactory.CreateDbContext();

                var exampleModel = new ExampleModel { Name = Guid.NewGuid().ToString() };

                dbContext.Examples.Add(exampleModel);

                dbContext.SaveChanges();
            }

            await Task.Delay(1000, stoppingToken);
        }
    }
}

The application was working perfectly in .NET 8, but after upgrading to .NET 9, this error started appearing. I suspect it might be related to changes in Dependency Injection or EF Core configuration. Could someone help identify the root cause and suggest a solution?

UPDATE: I have edited the question to include the example mentioned by @Guru Stron below. I noticed that if I remove AddDbContext in Program.cs, the error no longer occurs. However, I don’t understand why, as in .NET 8, I used both without any issues.

I recently upgraded my project from .NET 8 to .NET 9, and I encountered the following error when running my application:

Cannot resolve scoped service 'System.Collections.Generic.IEnumerable`1[Microsoft.EntityFrameworkCore.Infrastructure.IDbContextOptionsConfiguration`1[TestEFCore9Worker.Context.ExampleDbContext]]' from root provider.

Context: I'm using EF Core for database access. My ExampleDbContext is registered in the ServiceCollection using the following configuration in Program.cs:

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<Worker>();

builder.Services.AddDbContextFactory<ExampleDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DbConnectionString"));
});

builder.Services.AddDbContext<ExampleDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DbConnectionString"));
});

var host = builder.Build();
host.Run();

Below is the constructor of my ExampleDbContext. File ExampleDbContext.cs

public class ExampleDbContext : DbContext
{
    public ExampleDbContext(DbContextOptions options) : base(options)
    {
    }

    public required virtual DbSet<ExampleModel> Examples { get; set; }
}

In Worker.cs

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public Worker(ILogger<Worker> logger, IServiceScopeFactory serviceScopeFactory)
    {
        _logger = logger;
        _serviceScopeFactory = serviceScopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            }

            using (IServiceScope serviceScope = _serviceScopeFactory.CreateScope())
            {
                var dbContextFactory = serviceScope.ServiceProvider.GetRequiredService<IDbContextFactory<ExampleDbContext>>();
                using var dbContext = dbContextFactory.CreateDbContext();

                var exampleModel = new ExampleModel { Name = Guid.NewGuid().ToString() };

                dbContext.Examples.Add(exampleModel);

                dbContext.SaveChanges();
            }

            await Task.Delay(1000, stoppingToken);
        }
    }
}

The application was working perfectly in .NET 8, but after upgrading to .NET 9, this error started appearing. I suspect it might be related to changes in Dependency Injection or EF Core configuration. Could someone help identify the root cause and suggest a solution?

UPDATE: I have edited the question to include the example mentioned by @Guru Stron below. I noticed that if I remove AddDbContext in Program.cs, the error no longer occurs. However, I don’t understand why, as in .NET 8, I used both without any issues.

Share Improve this question edited Nov 18, 2024 at 8:47 Guru Stron 145k11 gold badges172 silver badges214 bronze badges asked Nov 17, 2024 at 13:10 ThangLeThangLe 1,0001 gold badge8 silver badges16 bronze badges 4
  • Can you please show the constructors of your CrawlerDbContext class? – Ricardo Peres Commented Nov 17, 2024 at 13:15
  • Hi @RicardoPeres, I updated the post (added picture about my DbContext. Thank you. – ThangLe Commented Nov 17, 2024 at 13:22
  • Do you have a minimal reproducible example you can share? – Guru Stron Commented Nov 17, 2024 at 18:39
  • Hi @GuruStron, thank you. I have updated the question and added more examples. While creating an example, I recognizednthat if I remove AddDbContext from the DI container, the bug disappears. However, I don’t understand why, as in my real project running on .NET 8, I use both AddDbContextFactory and AddDbContext without any issues. – ThangLe Commented Nov 18, 2024 at 4:14
Add a comment  | 

1 Answer 1

Reset to default 9

TL;DR

Remove the AddDbContext since it is not needed (or AddDbContextFactory if you actually do not need the factory =).

Details

I was able to repro the issue, not sure what has changed between the versions but arguably it does not actually matter, the thing is that AddDbContextFactory actually registers the context itself, there is no need to call AddDbContext (though AddDbContextFactory does not check presence of the ctor with options), so just remove the call:

builder.Services.AddHostedService<Worker>();

builder.Services.AddDbContextFactory<ExampleDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DbConnectionString"));
});

var host = builder.Build();

Also since you are manually creating the scope, in general there is no need to use factory in the provided code, just resolve the context itself:

using (IServiceScope serviceScope = _serviceScopeFactory.CreateScope())
{
    var dbContext = serviceScope.ServiceProvider.GetRequiredService<ExampleDbContext>();

    var exampleModel = new ExampleModel { Name = Guid.NewGuid().ToString() };

    dbContext.Examples.Add(exampleModel);

    dbContext.SaveChanges();
}

The IDbContextOptionsConfiguration was added in .NET 9 and seems to cause such regression.

Also seems to be related - Cannot remove DBContext from DI

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745633986a4637276.html

相关推荐

  • YashanDB 知识库|YMP 迁移报告无法下载?可能是你的 Java 版本“太新了”

    在使用 YMP 工具生成迁移报告时,部分用户在点击下载报告时遇到如下错误提示:“未知类型错误异常: ……(一长串英文)”虽然报错看起来很复杂,但背后的原因其实很简单:Java 版本不兼容。一、问题现象在 YMP 的 Web 控制台中,用户点

    1小时前
    00
  • YashanDB 知识库|共享集群换 IP 怎么操作?这篇教你全流程无坑换网段!

    当你从测试环境切到生产环境,IP 网段也会跟着发生变化。对于已经部署好的 YashanDB YAC 共享集群来说,IP 更换就是一项必须要面对的挑战。别担心,其实换 IP 没那么复杂,只需要分三步:改 yasboot、改数据库、改集群配置。

    1小时前
    00
  • YashanDB 知识库|YMP 报 YAS

    在使用 YMP 进行数据库迁移时,有用户在执行元数据阶段的索引创建操作时遭遇如下报错:YAS-04204 number of PARALLEL must be between 1 and 4这个错误通常出现在资源配置较小的环境中。别急,这其

    1小时前
    00
  • 运维实战来了|手把手教你构建 YashanDB 的 Prometheus Exporter

    今天和大家分享一位用户的实战投稿,主题是:如何从零构建一个适用于 YashanDB 的 Prometheus Exporter,打通监控全链路,打造更智能的数据库运维体系。一、为什么需要 YashanDB Exporter?在数据库运维中,

    1小时前
    00
  • YashanDB 知识库|数据误删别慌!一文教你搞定“表闪回”

    在日常开发或测试中,难免会出现误删表数据的情况。别急,YashanDB 支持灵活的表闪回功能,让你轻松恢复被误删的数据,不再手忙脚乱。以下结合实际场景,演示如何通过闪回查询、闪回表、回收站机制等手段,把误删的数据完美还原。一、删除操作下的数

    1小时前
    00
  • 全网首测!三大 AI 编程工具生成 SpringCloud 代码对比

    在当下软件开发领域,AI 编程工具正掀起一场革新风暴。对于 Java 开发者而言,构建基于 SpringCloud 的分布式系统是常见任务,而不同 AI 编程工具在这方面的表现大相径庭。此次,我们选取了三款国内颇具代表性的 AI 编程工具

    1小时前
    00
  • Windows下静默进程退出监控(SlientExit)

    Windows静默进程退出监控技术全解析通过注册表与API实现无感监控与内存转储一、技术背景静默进程退出(Silent Process Exit)是Windows 7开始引入的进程监控机制,可捕获两种特殊终止行为:自我终止:通过ExitPr

    1小时前
    20
  • Firebase Studio:谷歌掀起AI编程革命,全栈开发进入“零门槛”时代

    引言:当AI成为“首席架构师”2025年4月,谷歌在Google Cloud Next大会上发布Firebase Studio,这款集AI驱动、云端协作与全栈开发于一体的工具,被开发者誉为“AI时代的Visual Studio”。它不仅

    1小时前
    20
  • 一文看懂大模型核心参数调优用法与实战

    前言目前大部分集成大模型开发用作后端响应,基本上生产环境用的都是OpenAI Python 的SDK,我也推荐大家用OpenAI Python 的SDK,统一、规范易于理解。OpenAI的SDK是现在大模型生态建设的相对完善而且比较全面的,

    55分钟前
    00
  • Vulnhub靶机:Lower4

    Vulnhub简介Vulnhub是一个提供各种漏洞环境的靶场平台,大部分环境是做好的虚拟机镜像文件,镜像预先设计了多种漏洞,需要使用VMware或者VirtualBox运行。每个镜像会有破解的目标,挑战的目标是获取操作系统的root权限和查

    53分钟前
    00
  • 非靶向代谢组学—基础知识3(测序报告解读)

    非靶向代谢组学—基础知识3(测序报告解读)最近重新看了某测序公司的非靶向代谢组学的分析报告,感觉收获很大。这次就对非靶向代谢组学的常规下游分析内容进行一个整理,并不涉及代码,主要对基础概念的解读。1.代谢组学概述代谢组学(metabolom

    48分钟前
    00
  • 封号风暴再临:机器人玩家的生存现状与数据真相

    近日,微信封号风暴再次席卷而来,多个微信群中哀嚎遍野。作为微信机器人框架 WeChatFerry 的开发者,查克收集了大量数据,试图从中找出封号的规律。虽然这项调查类似于在心脏病科调查心脏病发病率——不是犯病或者怀疑犯病,谁会去看病呢。但毕

    34分钟前
    00
  • Windows11系统vmnetbridge.dll文件丢失问题

    其实很多用户玩单机游戏或者安装软件的时候就出现过这种问题&#xff0c;如果是新手第一时间会认为是软件或游戏出错了&#xff0c;其实并不是这样&#xff0c;其主要原因就是你电脑系统的该dll文件丢失了或没有安装一

    26分钟前
    00
  • 使用开源免费雷池WAF防火墙,接入保护你的网站

    使用开源免费雷池WAF防火墙,接入保护你的网站大家好,我是星哥,昨天介绍了《开源免费WEB防火墙,不让黑客越雷池一步!》链接:今天讲一下如何把网站接入到雷池WAF。首先需要安装雷池WAF。雷池工作原理(图)image-20250424190

    22分钟前
    00
  • HTML DOM 返回图像映射的某个区域的protocol 实例

    参考资料HTML DOM 节点列表长度HTML DOM 方法HTML DOM 返回文档中的链接数HTML DOM 返回加载的当前文档的URL实例HTML DOM 返回图像映射的某个区域的port 实例HTML DOM 返回一个锚的名字 实例

    15分钟前
    00
  • Abaqus做裂纹扩展仿真,只需要4步

    随着汽车工业的持续进步,轮胎作为车辆不可或缺的一部分,其性能标准也愈发严苛。在众多性能指标中,轮胎的疲劳破坏特性尤为引人瞩目,因为它直接关系到轮胎的可靠性和使用寿命。而整胎的疲劳破坏往往以橡胶基体的损坏为起点,Abaqus这意味着橡胶基体的

    14分钟前
    00
  • Bun:高性能 Go ORM 与 SQL 构建工具

    在 Go 生态中,传统的 ORM 往往要么“魔法”过多(如 GORM),要么过于模板化(如 SQLBoiler)。bun 则以 SQL-first 的设计理念,为开发者提供了轻量、高性能且灵活可控的 ORM 和查询构建器。它同时支持 Pos

    9分钟前
    00
  • 架构人生:我技术生涯中的那些第一次

    我从事软件开发这个工作已经20多年了,技术生涯中也经历过很多的第一次,回首往昔,每一个第一次我都记忆犹新、历历在目。这些第一次奠定了我的职业基础,也奠定了我的人生之路。写第一行职业代码我大学的专业是工业自动化,第一份工作是到一家国企做仪表工

    6分钟前
    00
  • 树莓派3b安装系统,远程操作,换源,出错调试流程

    前言 现市面上树莓派相关配置教程多而杂&#xff0c;新手用户缺少一个系统和完整的配置过程&#xff0c;本篇结合各种博文和个人踩坑经历,旨在帮助更多树莓派的新手玩家快速入门&#xff0c;也可以根据目录找到想要查

    1分钟前
    00
  • ascend cann镜像构建失败, 报错&quot;ImportError: libascend

    因为cann版本不匹配, vllm运行失败, 所以需要从头开始装cann. 在安装到deepspeed时, 报错"ImportError: libascend_hal.so: cannot open shared object f

    1分钟前
    00

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信