Polly and Blazor, Part 3 - Dependency Injection

Full source code available here.

Want to learn more about Polly? Check out my Pluralsight course on it.

This post continues to build on the two previous on using Polly with Blazor. The first was a simple example of using a Wait and Retry while updating the display as the policy retried, the second did the same but made use of the Polly Context. The Polly Context is something I have not made a lot of use of in the past, but I have a feeling that it will be very helpful with Blazor applications.

I’m keeping the examples similar, deliberately changing a single thing in each. In this post I will define the Wait and Retry Policy in the Startup, add it to the service collection and inject it into the Razor page.

One big difference to note is that I can no longer update the display from inside the OnRetry delegate of the Policy. Gone is the call to InvokeAsync(StateHasChanged) because this is dependent on the ComponentBase.

In Startup.cs add the following, it defines the Wait and Retry policy, and its OnRetry delegate -

 1public void ConfigureServices(IServiceCollection services)
 2    {
 3    IAsyncPolicy<HttpResponseMessage> _httpRequestPolicy = Policy.HandleResult<HttpResponseMessage>(
 4    r => !r.IsSuccessStatusCode)
 5    .WaitAndRetryAsync(3,
 6        retryAttempt => TimeSpan.FromSeconds(retryAttempt), onRetry: (response, retryDelay, retryCount, context) =>
 7        {
 8            context["message"] = context["message"] + $"\nReceived: {response.Result.StatusCode}, retryCount: {retryCount}, delaying: {retryDelay.Seconds} seconds";
 9        });
11    services.AddSingleton<IAsyncPolicy<HttpResponseMessage>>(_httpRequestPolicy);
12    // snip...

In the Razor section of the Index.razor page add this -

@inject IAsyncPolicy<HttpResponseMessage> _httpRequestPolicy

The policy will now be injected into the Razor page.

Using it is simple, see line 16 below -

 1@code {
 2   HttpClient httpClient = new HttpClient() {
 3        BaseAddress =  new Uri("http://localhost:5000")
 4    };
 6    private string status;
 7    private Context context = new Polly.Context("", new Dictionary<string, object>() {{"message",""}}); 
 8    private string responseCode;
 9    private string number;
11    private async Task CallRemoteServiceAsync()
12    {
13        status = "Calling remote service...";
14        string requestEndpoint = "faulty/";
16        HttpResponseMessage httpResponse = await _httpRequestPolicy.ExecuteAsync(ctx => httpClient.GetAsync(requestEndpoint), context);
17        responseCode = httpResponse.StatusCode.ToString();
18        number = await httpResponse.Content.ReadAsStringAsync();
19        status = "Finished";
20    }

Instead of injecting a Polly Policy, you could inject a Polly Registry with more than one policy. I have written about the registry a few times on this blog.

Full source code available here.

comments powered by Disqus