我收到此错误消息:
生成警告“Microsoft.EntityFrameworkCore.Infrastruct.ManyServiceProvidersCreatedWarning”错误:已创建超过二十个“IServiceProvider”实例供实体框架内部使用。这通常是由于将新的单例服务实例注入每个 DbContext 实例而引起的。例如,调用“UseLoggerFactory”每次都会传入一个新实例 - 有关更多详细信息,请参阅 https://go.microsoft.com/fwlink/?linkid=869049。这可能会导致性能问题,请考虑检查对“DbContextOptionsBuilder”的调用,这可能需要构建新的服务提供程序。通过将事件 ID“CoreEventId.ManyServiceProvidersCreatedWarning”传递给“DbContext.OnConfiguring”或“AddDbContext”中的“ConfigureWarnings”方法,可以抑制或记录此异常。
当我一起运行所有单元测试时
设置
private readonly DbContextOptions<ApplicationDbContext> _contextOptions;
private readonly DbContextOptions<ApplicationDbContext> _inMemoryContextOptions;
public TestConstructor()
{
// Test for real database READ
_contextOptions = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseSqlServer(_connectionString)
.Options;
// Test InMemory CREATE UPDATE DELETE
_inMemoryContextOptions = DbContextOptionsBuilder();
SeedInMemoryTestDb(_inMemoryContextOptions);
}
private static DbContextOptions<ApplicationDbContext> DbContextOptionsBuilder()
{
return new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString(),new InMemoryDatabaseRoot())
.Options;
}
单元测试
[FACT]
public void Test1()
await using var context = new ApplicationDbContext(_contextOptions);
//... Assert.Equal()
[FACT]
public void Test2()
await using var context = new ApplicationDbContext(_inMemoryContextOptions);
//... Assert.Equal()
我在 5 或 6 年级同时进行设置和单元测试。 我认为我需要为每个测试重新使用相同的上下文,但我没有做到这一点。
我也有同样的问题。我已经修复了这个问题,为我的测试 DatabaseFixture 提供了一个服务提供者,我在其中创建了 DatabaseContext
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkSqlServer()
.BuildServiceProvider();
var builder = new DbContextOptionsBuilder<BlogDBContext>();
builder.UseSqlServer(connectionString)
.UseInternalServiceProvider(serviceProvider); // <-- add this
[CollectionDefinition("SharedDbContext")]
public class DatabaseCollection : ICollectionFixture<DatabaseFixture> { }
public class DatabaseFixture : IDisposable
{
public ApplicationDbContext ApplicationDbContext;
public ApplicationDbContext InMemoryApplicationDbContext;
public DatabaseFixture()
{
// Test for real database READ
var contextOptions = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseSqlServer(_connectionString)
.Options;
//// Test InMemory CREATE UPDATE DELETE
var inMemoryContextOptions = DbContextOptionsBuilder();
ApplicationDbContext = new ApplicationDbContext(contextOptions);
InMemoryApplicationDbContext = new ApplicationDbContext(inMemoryContextOptions);
SeedInMemoryTestDb(inMemoryContextOptions);
}
}