Introduction
ShopNest Weather widget calls OpenWeather API — never new HttpClient() per request (socket exhaustion). Use IHttpClientFactory with typed clients and Polly resilience.
After this article you will
- Register typed HttpClient with IHttpClientFactory
- Deserialize JSON with System.Text.Json
- Add retry, timeout, and circuit breaker
- Pass API keys via configuration securely
- Mock HttpClient in unit tests
Prerequisites
- Article 40 — Pagination, Filtering and Sorting
- ShopNest with EF Core and auth from Modules 2–4
Concept deep-dive
public interface IWeatherClient
{
Task<WeatherDto?> GetCurrentAsync(string city, CancellationToken ct = default);
}
public class OpenWeatherClient : IWeatherClient
{
private readonly HttpClient _http;
public OpenWeatherClient(HttpClient http, IOptions<WeatherOptions> options)
{
_http = http;
_http.BaseAddress = new Uri("https://api.openweathermap.org/data/2.5/");
}
public async Task<WeatherDto?> GetCurrentAsync(string city, CancellationToken ct)
{
var response = await _http.GetAsync($"weather?q={Uri.EscapeDataString(city)}&appid=...", ct);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<WeatherDto>(cancellationToken: ct);
}
}
builder.Services.AddHttpClient<IWeatherClient, OpenWeatherClient>(client =>
{
client.Timeout = TimeSpan.FromSeconds(10);
})
.AddStandardResilienceHandler(); // .NET 8 Polly integration
Hands-on — ShopNest Weather Integration App
- WeatherOptions with ApiKey in User Secrets.
- WeatherController returns cached forecast for ShopNest homepage.
- Simulate 503 — verify retry then circuit opens.
- Unit test with MockHttpMessageHandler.
Common errors & best practices
- new HttpClient() in using block per call — DNS/socket issues under load.
- API key in query string logged — prefer header where provider allows.
- No timeout — hung threads block request pool.
Interview questions
Q: Why IHttpClientFactory?
A: Manages HttpClient lifetime and handler rotation — avoids socket exhaustion.
Q: Typed vs named client?
A: Typed binds interface to implementation; named uses string key — typed is cleaner.
Q: Circuit breaker?
A: Stops calling failing external API temporarily — fail fast protects ShopNest.
Summary
- IHttpClientFactory is the correct HttpClient pattern
- Typed clients + options for OpenWeather integration
- Resilience handlers add retry and circuit breaker
- Mock handlers enable fast unit tests without network
Previous: Pagination, Filtering and Sorting
Next: Minimal APIs
FAQ
Polly vs StandardResilienceHandler?
.NET 8 Microsoft.Extensions.Http.Resilience wraps Polly — prefer for new apps.
Cache external API responses?
IMemoryCache with TTL reduces rate limits and latency.