https://github.com/soenneker/soenneker.utils.httpclientcache
A utility library for singleton thread-safe HttpClients
https://github.com/soenneker/soenneker.utils.httpclientcache
csharp dotnet httpclient utils
Last synced: 2 months ago
JSON representation
A utility library for singleton thread-safe HttpClients
- Host: GitHub
- URL: https://github.com/soenneker/soenneker.utils.httpclientcache
- Owner: soenneker
- License: mit
- Created: 2023-10-01T01:04:37.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2026-04-14T20:12:55.000Z (3 months ago)
- Last Synced: 2026-04-14T20:22:58.416Z (3 months ago)
- Topics: csharp, dotnet, httpclient, utils
- Language: C#
- Homepage: https://soenneker.com
- Size: 2.14 MB
- Stars: 1
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Contributing: .github/CONTRIBUTING.md
- Funding: .github/FUNDING.yml
- License: LICENSE
- Code of conduct: .github/CODE_OF_CONDUCT.md
- Security: .github/SECURITY.md
Awesome Lists containing this project
README
[](https://www.nuget.org/packages/Soenneker.Utils.HttpClientCache/)
[](https://github.com/soenneker/soenneker.utils.httpclientcache/actions/workflows/publish-package.yml)
[](https://www.nuget.org/packages/Soenneker.Utils.HttpClientCache/)
[](https://github.com/soenneker/soenneker.utils.httpclientcache/actions/workflows/codeql.yml)
#  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. `HttpClient`s are created lazily, and disposed on application shutdown (or manually if you want).
See [Guidelines for using HttpClient](https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines)
## Installation
```
dotnet add package Soenneker.Utils.HttpClientCache
```
## Usage
1. Register `IHttpClientCache` within DI (`Program.cs`).
```csharp
public static async Task Main(string[] args)
{
...
builder.Services.AddHttpClientCache();
}
```
2. Inject `IHttpClientCache` via constructor, and retrieve a fresh `HttpClient`.
Example:
```csharp
public class TestClass
{
IHttpClientCache _httpClientCache;
public TestClass(IHttpClientCache httpClientCache)
{
_httpClientCache = httpClientCache;
}
public async ValueTask 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;
}
}
```