'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
dotnet add package Soenneker.Utils.HttpClientCache
- Register
IHttpClientCachewithin DI (Program.cs).
public static async Task Main(string[] args)
{
...
builder.Services.AddHttpClientCache();
}- Inject
IHttpClientCachevia constructor, and retrieve a freshHttpClient.
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;
}
}