C# / .NET Compendium PLEN
.NET / C# / Refresher / web patterns

Code Review - an example with HttpClientFactory anti-patterns

The code under review

public class WeatherApiClient
{
    private readonly HttpClient _httpClient;

    // ❌ PROBLEM 1: a public parameterless constructor creating ITS OWN HttpClient
    public WeatherApiClient()
    {
        _httpClient = new HttpClient();
        _httpClient.BaseAddress = new Uri("https://api.weather.com/");
    }

    public async Task<WeatherDto> GetWeatherAsync(string city)
    {
        try
        {
            var response = await _httpClient.GetAsync($"weather?city={city}");
            var json = await response.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<WeatherDto>(json);
        }
        catch (Exception ex) // ❌ PROBLEM 2: catching ALL exceptions, misleading error handling
        {
            Console.WriteLine("Error: " + ex.Message);
            return null; // ❌ PROBLEM 3: hides the error, the caller doesn't know WHAT failed
        }
    }
}

Problem #1: Socket Exhaustion - new HttpClient() in the constructor

This is the most critical and most frequently asked problem in .NET/Web API interviews. HttpClient implements IDisposable, so intuitively someone might think it should be wrapped in a using on every use:

// ❌ EVEN WORSE - if someone "fixes" it with using
public async Task<WeatherDto> GetWeatherAsync(string city)
{
    using var httpClient = new HttpClient(); // a NEW client on EVERY call!
    // ...
}

Why this is catastrophic: every creation of an HttpClient creates a new network socket. The operating system doesn't release sockets immediately after the connection is closed - they enter the TIME_WAIT state (typically 240 seconds on Windows). Under heavy traffic (hundreds/thousands of requests per minute), the application exhausts the operating system's available ports/sockets, which leads to SocketException: Address already in use or a general hang of the application under load.

This is exactly the problem we discussed with Singleton/thread-safety - HttpClient is designed to be reusable and thread-safe for many concurrent requests - creating a new instance on every call negates that advantage.

The correct solution - IHttpClientFactory

// Program.cs - rejestracja
builder.Services.AddHttpClient<IWeatherApiClient, WeatherApiClient>(client =>
{
    client.BaseAddress = new Uri("https://api.weather.com/");
});
public class WeatherApiClient : IWeatherApiClient
{
    private readonly HttpClient _httpClient;

    // ✅ Constructor injection - the HttpClient is INJECTED, not created by hand
    public WeatherApiClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<WeatherDto> GetWeatherAsync(string city)
    {
        var response = await _httpClient.GetAsync($"weather?city={city}");
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<WeatherDto>();
    }
}

IHttpClientFactory (registered through AddHttpClient<TInterface, TImplementation>) manages a pool of HTTP handlers underneath - it reuses TCP connections between requests, while also automatically refreshing the handlers after a while (2 minutes by default) to respect DNS changes (which is a problem if HttpClient were a pure Singleton living forever without refreshing).

Problem #2: An overly general catch (Exception) - misleading error handling

catch (Exception ex) // catches EVERYTHING - including OutOfMemoryException, StackOverflowException...
{
    Console.WriteLine("Error: " + ex.Message);
    return null;
}

Why this is problematic: 1. Catching too broad a category of exceptions - catch (Exception) intercepts everything, including programming errors (NullReferenceException, ArgumentException), which should blow up loudly in development rather than be "swallowed" 2. Console.WriteLine as "logging" - in a real server application this is useless (nobody reads the console of a production server) - it should be ILogger<T> (injected through DI, as we discussed) 3. Returning null on error - this is Problem #3, see below

The corrected approach - selective error handling

public async Task<WeatherDto> GetWeatherAsync(string city)
{
    try
    {
        var response = await _httpClient.GetAsync($"weather?city={city}");
        response.EnsureSuccessStatusCode(); // rzuci HttpRequestException dla 4xx/5xx
        return await response.Content.ReadFromJsonAsync<WeatherDto>();
    }
    catch (HttpRequestException ex) // ✅ a SPECIFIC exception type, an expected scenario
    {
        _logger.LogWarning(ex, "Failed to fetch the weather for the city {City}", city);
        throw new WeatherServiceUnavailableException(city, ex); // translated into a DOMAIN exception
    }
    // UNexpected exceptions (NullReferenceException etc.) PROPAGATE, they are not "swallowed"
}

Problem #3: Returning null on error - hiding information about the failure

return null; // the caller DOESN'T KNOW whether: (a) the city doesn't exist, (b) the API went down, (c) a network error

The consequence for the calling code:

var weather = await _weatherApiClient.GetWeatherAsync("Warszawa");
Console.WriteLine(weather.Temperature); // ❌ NullReferenceException if GetWeatherAsync returned null!

The caller has to remember to check for null everywhere it uses this method - and doesn't know why it got null (the city doesn't exist? the service went down? a network error?) - this makes an appropriate reaction harder (e.g. "try again" for a network error vs "show an error to the user" for a nonexistent city).

A better approach - Result<T> (a link to the earlier discussion of ActionResult on the client side)

public async Task<ApiResult<WeatherDto>> GetWeatherAsync(string city)
{
    try
    {
        var response = await _httpClient.GetAsync($"weather?city={city}");

        if (response.StatusCode == HttpStatusCode.NotFound)
            return ApiResult<WeatherDto>.Failure($"City '{city}' was not found", response.StatusCode);

        response.EnsureSuccessStatusCode();
        var weather = await response.Content.ReadFromJsonAsync<WeatherDto>();
        return ApiResult<WeatherDto>.Success(weather, response.StatusCode);
    }
    catch (HttpRequestException ex)
    {
        _logger.LogWarning(ex, "A connection error while fetching the weather for {City}", city);
        return ApiResult<WeatherDto>.Failure("The weather service is unavailable", HttpStatusCode.ServiceUnavailable);
    }
}

The caller explicitly gets information about the kind of failure, exactly as in the ApiResult<T> example we discussed with consuming an ActionResult on the client side.

A combined summary of the problems and fixes

Problem Consequence Solution
new HttpClient() in the constructor Socket exhaustion under load IHttpClientFactory through AddHttpClient<T>(), an injected HttpClient
A general catch (Exception) Catches programming errors, makes debugging harder Catch specific exception types (HttpRequestException), the rest propagates
Console.WriteLine as logging Useless in production ILogger<T> through DI
return null on error Hides the cause, forces null checks everywhere Result<T>/a domain exception with clear information about the cause

Why this kind of question is common in SE III interviews

A code review is a practical test integrating many topics at once - this one fragment of code touches: resource management (HttpClient/DI), good exception-handling practices, the quality of logging, and the design of returned values in APIs (null vs Result<T>). A good answer in an interview doesn't end at "HttpClient should come from DI" - it shows an understanding of all the layers of the problem and why each fix matters in the context of a production application under load.

Buy me a coffee