Skip to content

soenneker/soenneker.utils.httpclientcache

Repository files navigation

Soenneker.Utils.HttpClientCache

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

  1. Register IHttpClientCache within DI (Program.cs).
public static async Task Main(string[] args)
{
    ...
    builder.Services.AddHttpClientCache();
}
  1. Inject 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;
    }
}

About

A utility library for singleton thread-safe HttpClients

Topics

Resources

License

Stars

Watchers

Forks

Languages