注册 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);
}
}
找到原因了,集成测试所测试的 web api 项目的 Program 中使用了 AddDbContextPool
,而在集成测试的 BlogSiteWebApplicationFactory
的 ConfigureWebHost
中依然在使用 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));