Providing thread-safe singleton HttpClients
Why?
'Long-lived' HttpClient static/singleton instances is the recommended use pattern in .NET. Avoid the unnecessary overhead of IHttpClientFactory, and definitely avoid creating a new HttpClient instance per request.
HttpClientCache provides a thread-safe singleton HttpClient instance per key via dependency injection. HttpClients are created lazily, and disposed on application shutdown (or manually if you want).
See Guidelines for using HttpClient
Installation
dotnet add package Soenneker.Utils.HttpClientCache
Usage
- Register
IHttpClientCachewithin DI (Program.cs).
{
...
builder.Services.AddHttpClientCache();
}
- Inject
IHttpClientCachevia constructor, and retrieve a freshHttpClient.
Example:
{
IHttpClientCache _httpClientCache;
public TestClass(IHttpClientCache httpClientCache)
{
_httpClientCache = httpClientCache;
}
public async ValueTask<string> GetGoogleSource()
{
HttpClient httpClient = await _httpClientCache.Get(nameof(TestClass));
var response = await httpClient.GetAsync("https://www.google.com");
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}