gpt4 book ai didi

c# - 在 ASP.NET Core WebApplicationFactory 中覆盖 EF Core DbContext

转载 作者:行者123 更新时间:2023-12-04 11:05:11 29 4
gpt4 key购买 nike

我有一个 ASP.NET Core 2.2 WebApi 项目,它也使用 EF Core 2.2。该项目通过集成测试进行了测试 WebApplicationFactory<T> .

我尝试将 web api 项目迁移到 netcore/aspnetcore 3,效果很好。我偶然发现的是迁移测试。

我有以下在 aspnetcore 2.2 中工作的代码:

    public class MyServiceWebHostFactory : WebApplicationFactory<Service.Startup>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();

services.AddDbContext<MyContext>((options, context) =>
{
context.UseInMemoryDatabase("MyDb")
.UseInternalServiceProvider(serviceProvider);
});

var sp = services.BuildServiceProvider();

using var scope = sp.CreateScope();

var scopedServices = scope.ServiceProvider;

// try to receive context with inmemory provider:
var db = scopedServices.GetRequiredService<MyContext>();

// more code...

// Ensure the database is created.
//db.Database.EnsureCreated();

// more code...
});
}
}

它使用 InMemoryProvider 将 EF Core DbContext 替换为 DbContext。

迁移到 3.0 后,它不再被替换。我总是收到配置了 SQL Server 的 DBContext。

如果我删除 services.AddDbContext<MyContext>(options => options.UseSqlServer(connectionString))调用 ConfigureServices在应用程序 ( Service.Startup ) 中它可以工作,但这不是解决方案。

我也试过 services.RemoveAll(typeof(MyContext))在注册也不起作用的内存上下文之前。

最佳答案

更新的文档位于 https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1可能会有所帮助。关键片段变化是去掉之前的上下文服务注册:

// Remove the app's ApplicationDbContext registration.
var descriptor = services.SingleOrDefault(
d => d.ServiceType ==
typeof(DbContextOptions<ApplicationDbContext>));

if (descriptor != null)
{
services.Remove(descriptor);
}

// Add ApplicationDbContext using an in-memory database for testing.
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseInMemoryDatabase("InMemoryDbForTesting");
});

// Build the service provider.
var sp = services.BuildServiceProvider();

关于c# - 在 ASP.NET Core WebApplicationFactory 中覆盖 EF Core DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58375527/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com