Skip to content

Latest commit

 

History

History
53 lines (35 loc) · 2.33 KB

File metadata and controls

53 lines (35 loc) · 2.33 KB
title HCR084 — Avoid duplicated named HttpClient string literals
description Repeated named-client string literals drift; prefer a shared constant for IHttpClientFactory.CreateClient names.

HCR084

Avoid duplicated string literals for named HttpClient names.

Why

Named clients depend on the same name being used at registration and at IHttpClientFactory.CreateClient(...) call sites. Repeating the name as string literals makes drift easy during refactors and harder to find in review.

Bad

services.AddHttpClient("payments");

public HttpClient Create(IHttpClientFactory factory)
{
    return factory.CreateClient("payments");
}

Better

public static class HttpClientNames
{
    public const string Payments = "payments";
}

services.AddHttpClient(HttpClientNames.Payments);

public HttpClient Create(IHttpClientFactory factory)
{
    return factory.CreateClient(HttpClientNames.Payments);
}

Current Detection

The implementation reports IHttpClientFactory.CreateClient("name") string literals and compile-time string constants (including constants declared in another source file), concatenations, conditionals, or interpolations when the same name is used in a visible AddHttpClient("name") registration in the compilation. Both registration and usage names may be reached through visible, cycle-safe local initializers or split direct assignments when no later mutation obscures the value. Parentheses and null-forgiving operators are transparent around inline and local name expressions.

It validates Microsoft.Extensions.DependencyInjection.IServiceCollection and System.Net.Http.IHttpClientFactory receivers when semantic information is available, requires resolved registrations to return IHttpClientBuilder, skips shared constants at usage sites, ambiguously mutated or otherwise unresolved local names, runtime-computed name expressions, and skips resolved custom registration or factory lookalikes, including same-named types declared in other namespaces and custom CreateClient extension overloads.

Suppression

Suppress only when the literal is intentionally duplicated in a very small scope and introducing a shared constant would reduce clarity.

References