gpt4 book ai didi

asp.net-core - 在 ASP.NET Core 集成测试中从 WebApplicationFactory 获取服务

转载 作者:行者123 更新时间:2023-12-03 23:33:21 29 4
gpt4 key购买 nike

我想使用 WebApplicationFactory<T> 设置我的测试如详述
Integration tests in ASP.NET Core .

在我的一些测试之前,我需要使用在真正的 Startup 类中配置的服务来进行设置。
我的问题是我看不到从工厂获得服务的方法。

我可以从 factory.Server 获得服务使用 factory.Host.Services.GetRequiredService<ITheType>();除了 factory.Serverfactory.CreateClient(); 之前为空已被调用。

有什么方法可以让我使用工厂获得服务吗?

谢谢。

最佳答案

您需要创建一个 范围从服务提供商处获得必要的服务:

using (var scope = AppFactory.Server.Host.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<MyDatabaseContext>();
}

关于asp.net-core - 在 ASP.NET Core 集成测试中从 WebApplicationFactory<T> 获取服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52745379/

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