In this lesson, you will learn how to make your Blazor data services robust by using IHttpClientFactory paired with Polly to automatically handle transient network failures.
When your Blazor application consumes external APIs, network hiccups—like a brief DNS timeout or a server overload—can crash your user experience. Instead of manually writing try-catch blocks in every service, we use a resilient pipeline that intercepts outgoing requests.
The Power of the Pipeline
By integrating Polly into your HttpClientFactory registration, you create a "middleware" for your HTTP traffic. You define policies that act like guardrails:
- Retry Policy: If a request fails due to a transient error (like a 503 Service Unavailable), the pipeline automatically waits and tries again.
- Circuit Breaker: If a service is down, the pipeline "trips the circuit," immediately failing subsequent requests for a period. This prevents your Blazor app from wasting resources waiting on a service you already know is offline.
Configuring the Pipeline
In your Program.cs, you register a named or typed HttpClient and attach these policies:
builder.Services.AddHttpClient<WeatherService>(client =>
{
client.BaseAddress = new Uri("https://api.example.com/");
})
.AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(3, _ => TimeSpan.FromMilliseconds(500)))
.AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)));
In this example, the WeatherService now benefits from a three-strike retry logic. If it fails consecutively five times, the circuit breaker opens for 30 seconds, protecting your Blazor UI from unnecessary hangs.
Because this logic is encapsulated within the HttpClient registration, your WeatherService stays clean and focused on data logic rather than infrastructure concerns. The component calling GetWeatherAsync() doesn’t need to know if the request succeeded on the first try or the third; it simply receives the data or an exception after the pipeline has exhausted its retries.
Key Takeaway: By chaining Polly policies to your HttpClientFactory in Program.cs, you build a declarative, self-healing communication layer that isolates your Blazor components from transient network instability.