首页 新闻 会员 周边 捐助

.NET: 使用 AddDbContextPool 遇到错误 "Cannot consume scoped service"

0
悬赏园豆:30 [已解决问题] 解决于 2024-01-28 06:55

注册 EF Core 的 DbContext 时将 AddDbContext 改为 AddDbContextPool 后集成测试出现下面的错误:

   System.AggregateException : Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.EntityFrameworkCore.Internal.IDbContextPool`1[Cnblogs.BlogServer.BlogSites.Infrastructure.BlogSiteDbContext] Lifetime: Singleton ImplementationType: Microsoft.EntityFrameworkCore.Internal.DbContextPool`1[Cnblogs.BlogServer.BlogSites.Infrastructure.BlogSiteDbContext]': Cannot consume scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Cnblogs.BlogServer.BlogSites.Infrastructure.BlogSiteDbContext]' from singleton 'Microsoft.EntityFrameworkCore.Internal.IDbContextPool`1[Cnblogs.BlogServer.BlogSites.Infrastructure.BlogSiteDbContext]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.EntityFrameworkCore.Internal.IScopedDbContextLease`1[Cnblogs.BlogServer.BlogSites.Infrastructure.BlogSiteDbContext] Lifetime: Scoped ImplementationType: Microsoft.EntityFrameworkCore.Internal.ScopedDbContextLease`1[Cnblogs.BlogServer.BlogSites.Infrastructure.BlogSiteDbContext]': Cannot consume scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Cnblogs.BlogServer.BlogSites.Infrastructure.BlogSiteDbContext]' from singleton 'Microsoft.EntityFrameworkCore.Internal.IDbContextPool`1[Cnblogs.BlogServer.BlogSites.Infrastructure.BlogSiteDbContext]'.)

请问如何解决?

问题补充:

异常发生于集成测试中下面的代码 Services.CreateScope()

public class BlogSiteWebApplicationFactory : WebApplicationFactory<Program>
{
    public void ConfigureDbContext(Action<BlogSiteDbContext> seedWork)
    {
        using var scope = Services.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<BlogSiteDbContext>();
        seedWork.Invoke(db);
    }
}
dudu的主页 dudu | 高人七级 | 园豆:31030
提问于:2024-01-27 22:44
< >
分享
最佳答案
0

找到原因了,集成测试所测试的 web api 项目的 Program 中使用了 AddDbContextPool,而在集成测试的 BlogSiteWebApplicationFactoryConfigureWebHost 中依然在使用 AddDbContext

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
    builder.ConfigureServices(
        services =>
        {
            services.AddDbContext<BlogSiteDbContext>(options => options.UseSqlite(connection));
        });
}

改为统一使用 AddDbContextPool 就解决了

services.AddDbContextPool<BlogSiteDbContext>(options => options.UseSqlite(connection));
dudu | 高人七级 |园豆:31030 | 2024-01-28 06:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册