Providing thread-safe singleton HttpClients
$ dotnet add package Soenneker.Utils.HttpClientCache
Soenneker.Utils.HttpClientCache'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
dotnet add package Soenneker.Utils.HttpClientCache
IHttpClientCache within DI (Program.cs).public static async Task Main(string[] args)
{
...
builder.Services.AddHttpClientCache();
}IHttpClientCache via constructor, and retrieve a fresh HttpClient.Example:
public class TestClass
{
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;
}
}