如何从CustomWebApplicationFactory获取所有服务? 启动类对IDepartmentRepository和IDepartmentAppService进行了依赖项注入。想获取新的DI存储库或服务。
我们正在创建指向原始应用程序启动的集成测试。
namespace Integrationtest
{
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration((hostingContext, configurationBuilder) =>
{
var type = typeof(TStartup);
var path = @"C:\\OriginalApplicationWebAPI";
configurationBuilder.AddJsonFile($"{path}\\appsettings.json", optional: true, reloadOnChange: true);
configurationBuilder.AddEnvironmentVariables();
});
}
}
}
public class DepartmentAppServiceTest : IClassFixture<CustomWebApplicationFactory<OriginalApplication.Startup>>
{
public testDbContext context;
private readonly HttpClient _client;
public DepartmentAppServiceTest(CustomWebApplicationFactory<OriginalApplication.Startup> factory)
{
_client = factory.CreateClient();
factory. // trying to find services here for IDepartmentRepository
}
https://fullstackmark.com/post/20/painless-integration-testing-with-aspnet-core-web-api
答案 0 :(得分:1)
它是factory.Host.Services
。不要忘记,您将需要创建一个范围来访问范围化服务,例如您的上下文:
using (var scope = _factory.Host.Services.CreateScope())
{
var foo = scope.ServiceProvider.GetRequiredService<Foo>();
// do something
}
答案 1 :(得分:0)
收到的错误:
'CustomWebApplicationFactory'不包含'Host'的定义,找不到可以接受的扩展方法'Host'接受类型为'CustomWebApplicationFactory'的第一个参数(您是否缺少using指令或程序集引用?)>
因此,我必须将其与添加的服务器一起使用,如下所示:
using (var scope = _factory.Server.Host.Services.CreateScope())
{
// do something
}