在開發ASP.NET專案時,常常會使用HttpClient來call API。但HttpClient不像SqlConnect底層有connection pool的機制,若每次使用完馬上關閉連線,下次使用時還要耗費額外的資源重新開啟連線,但一直保持連線開啟又可能耗盡資源。在.net core2.1後新增的HttpClientFactory可以統一管理HttpClient的連線。
在.net core要使用HttpClientFactory的話,首先在Startup.cs中把HttpClient加入容器
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
}
在constructer注入IHttpClientFactory
public HomeController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
之後的使用方式就跟HttpClient一樣了
HttpClient httpClient = _httpClientFactory.CreateClient();
另外在ConfigureServices加入時可以一併設定HttpClient的預設值,如bearer token之類的,也可以建立具名的HttpClient
services.AddHttpClient("MyApiService", config =>
{
config.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
});
使用時只要指定名稱就可以了
HttpClient httpClient = _httpClientFactory.CreateClient("MyApiService");
如果要在.net專案使用HttpClientFactory的話可以參考這篇
參考資料:
- https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests
- https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0
- https://blog.yowko.com/httpclientfactory-dotnet-core-dotnet-framework/