Polly and Blazor, Part 2 – Using the Context
Full source code available here.
Want to learn more about Polly? Check out my Pluralsight course on it.
This post is a short follow-up to the one where I used Polly Wait and Retry in Blazor. In that post I used variables defined in my C# method to pass information back to the calling code, to display on the screen. But here I’m going to show how the Polly Context can be used instead.
The setup and almost all the code is the same, so please take a look at that post.
Using the Context
The Razor
section references the message in the Polly context rather than a defined variable for the message -
1<p>Polly Summary : @context["message"]</p>
In the code
block add a Polly Context and initialize the dictionary with a message, this is important because the Razor block references this message when the page loads.
1@code {
2 //snip...
3
4 private Context context = new Polly.Context("", new Dictionary<string, object>() {{"message",""}});
5 //snip...
Then in the rest of the code block, update the message in the context with the information to display to the user.
1private async Task CallRemoteServiceAsync()
2{
3 IAsyncPolicy<HttpResponseMessage> _httpRequestPolicy = Policy.HandleResult<HttpResponseMessage>(
4 r => !r.IsSuccessStatusCode)
5 .WaitAndRetryAsync(3,
6 retryAttempt => TimeSpan.FromSeconds(retryAttempt * 2), onRetry: (response, retryDelay, retryCount, context) => {
7 context["message"] = $"Recieved: {response.Result.StatusCode}, retryCount: {retryCount}, delaying: {retryDelay.Seconds} seconds\n";
8 Console.WriteLine(context["message"]);
9 InvokeAsync(StateHasChanged);
10 });
11 status = "Calling remote service...";
12 string requestEndpoint = "faulty/";
13 HttpResponseMessage httpResponse = await _httpRequestPolicy.ExecuteAsync(ctx => httpClient.GetAsync(requestEndpoint), context);
14 responseCode = httpResponse.StatusCode.ToString();
15 number = await httpResponse.Content.ReadAsStringAsync();
16 status = "Finished";
17 context["message"] = "";
18}
That’s it, another way to do the same thing.
In the next post, I’ll show how to use a Polly Policy defined within the OnInitializedAsync
block.
Full source code available here.