Skip to content

HCR001

Do not create and dispose HttpClient per request.

Why

Creating short-lived HttpClient instances in request paths can contribute to socket exhaustion and connection churn. Prefer IHttpClientFactory, typed clients, named clients, or a long-lived manually configured client.

Bad

public sealed class PaymentsService
{
    public async Task<string> GetAsync(CancellationToken cancellationToken)
    {
        using var client = new HttpClient();
        return await client.GetStringAsync("https://example.com", cancellationToken);
    }
}

Better

public sealed class PaymentsService(HttpClient client)
{
    public Task<string> GetAsync(CancellationToken cancellationToken)
    {
        return client.GetStringAsync("https://example.com", cancellationToken);
    }
}

Current Detection

The implementation reports high-confidence new HttpClient() usage when it appears in likely request-path types, inside loops, Minimal API endpoint lambdas, or using ownership patterns, including top-level statement loops and using var declarations. Health checks that implement Microsoft.Extensions.Diagnostics.HealthChecks.IHealthCheck, either directly or through an inherited interface, are also treated as request-path types because probe requests run them repeatedly; the interface is resolved by symbol, so a custom interface that happens to be named IHealthCheck does not trigger the rule. Constructor assignments to an instance field or property, or to a static field in a static constructor, are treated as a client retained for the containing type's lifetime and are skipped because the owner's DI lifetime is not provable from the compilation. Instance clients assigned in a controller constructor are still reported because MVC constructs controllers per request, and creations in loops or lambdas are still reported as per-call work. Minimal API endpoint detection is limited to visible MapGet/MapPost-style calls on common endpoint-builder receivers such as app or IEndpointRouteBuilder declarations, including visible route-group chains and route-group locals created from MapGroup(...); parentheses and null-forgiving operators are transparent around those receivers. Resolved custom types named HttpClient are skipped. Test code is ignored: types ending with Test or Tests, common attributed xUnit, NUnit, and MSTest contexts such as [Fact], [Theory], [Test], [TestFixture], [SetUp], [TestMethod], [TestInitialize], [TestCleanup], and [TestClass], types deriving from a test-named base type, types in a Test, Tests, Testing, *Test, or *Tests namespace, and files under a test, tests, testassets, testapps, or acceptance directory.

Known Limitations

  • Test-support libraries that do not look like test code are not skipped. Dapr.Testcontainers creates and disposes an HttpClient to pull a model from a container fixture and reports because its name, namespace, and path are not test-shaped.
  • Detection of short-lived clients is shape-based: request-path types, loops, endpoint lambdas, and using ownership. A client created in a helper and returned to a request path is reported from the creation site only when that site matches one of those shapes.
  • Constructor assignments to fields and properties are treated as long-lived unless the type looks like a per-request controller. Other owner lifetimes cannot be proved from a single compilation.
  • Health-check detection needs a resolved IHealthCheck interface. A wrapper interface that does not derive from Microsoft.Extensions.Diagnostics.HealthChecks.IHealthCheck, or a type whose interface cannot be resolved, is not treated as a health check.

Code Fix

When the nearest containing local function or method, or the class primary constructor, already has an IHttpClientFactory parameter, the code fix replaces new HttpClient() with <factoryParameter>.CreateClient(string.Empty). The empty name selects the default client, which is the closest equivalent to a bare new HttpClient(); IHttpClientFactory.CreateClient has no parameterless overload. This nearest-scope selection keeps a local function's factory parameter from accidentally being replaced with an outer method parameter. When no parameter is in scope, the fix reuses a readable, non-nullable IHttpClientFactory-typed field or property declared on the containing type — preferring members whose name contains Factory, otherwise ordering by name — and skips members shadowed by an in-scope local or parameter. The fix is not offered in static contexts and does not add constructor parameters or change DI registrations automatically.

For example, a primary-constructor factory parameter is reused without changing the constructor:

public sealed class PaymentsService(IHttpClientFactory factory)
{
    public HttpClient Create() => new HttpClient();
}

The code action produces:

public sealed class PaymentsService(IHttpClientFactory factory)
{
    public HttpClient Create() => factory.CreateClient(string.Empty);
}

Suppression

Suppress only for non-production sample code, tests, or deliberately isolated one-off tooling where connection reuse is not relevant.

References