如何從 CustomWebApplicationFactory 獲取所有服務?Startup類對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
2 回答

皈依舞
TA貢獻1851條經驗 獲得超3個贊
是factory.Host.Services。不要忘記,您需要創建一個范圍來訪問范圍服務,例如您的上下文:
using (var scope = _factory.Host.Services.CreateScope())
{
var foo = scope.ServiceProvider.GetRequiredService<Foo>();
// do something
}

慕標5832272
TA貢獻1966條經驗 獲得超4個贊
收到錯誤:
“CustomWebApplicationFactory”不包含“Host”的定義,并且找不到接受“CustomWebApplicationFactory”類型的第一個參數的可訪問擴展方法“Host”(您是否缺少 using 指令或程序集引用?)
因此,我必須在添加服務器的情況下使用它,如下所示:
using (var scope = _factory.Server.Host.Services.CreateScope()) { // do something }
- 2 回答
- 0 關注
- 148 瀏覽
添加回答
舉報
0/150
提交
取消