Dark Mode

Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

Readme

License

MIT license

Code of conduct

Code of conduct

Contributing

Contributing

Security policy

Security policy

Stars

Watchers

Forks

Sponsor this project

Packages

Contributors

Languages