Asp.net-Core

在 ASP.NET Core 集成測試中從 WebApplicationFactory<T> 獲取服務

  • October 10, 2018

我想使用ASP.NET CoreWebApplicationFactory&lt;T&gt;中的集成測試中的詳細說明 來設置我的測試。

在我的一些測試之前,我需要使用在真正的 Startup 類中配置的服務來進行設置。我遇到的問題是我看不到從工廠獲得服務的方法。

我可以從factory.Server使用中獲得一項服務,factory.Host.Services.GetRequiredService&lt;ITheType&gt;();除非它factory.Server是空的,直到factory.CreateClient();被呼叫。

我有什麼方法可以使用工廠獲得服務嗎?

謝謝。

您需要從服務提供者創建一個範圍以獲得必要的服務:

using (var scope = AppFactory.Server.Host.Services.CreateScope())
{
   var context = scope.ServiceProvider.GetRequiredService&lt;MyDatabaseContext&gt;();
}

引用自:https://stackoverflow.com/questions/52745379