Polly with .NET 6, Part 7 - Policy Wraps with Minimal APIs, and HttpClientFactory

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

This post is very similar to the previous one, but I want to show how to use the Policy Wrap with the HttpClientFactory.

First, add the Microsoft.Extensions.Http.Polly package to your project. That will bring in all the other dependencies you need.

See below for a explanation of the code.

 1using System.Net;
 2using Polly;
 3using Polly.Extensions.Http;
 4
 5var builder = WebApplication.CreateBuilder(args);
 6
 7IAsyncPolicy<HttpResponseMessage> httpRetryPolicy = HttpPolicyExtensions
 8    .HandleTransientHttpError()
 9    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt));
10
11IAsyncPolicy<HttpResponseMessage> httpRequestFallbackPolicy = 
12    HttpPolicyExtensions.HandleTransientHttpError()
13    .FallbackAsync(new HttpResponseMessage(HttpStatusCode.OK)
14    {
15        Content = new StringContent("-1")
16    });
17
18IAsyncPolicy<HttpResponseMessage> retryAndFallbackWrap = 
19    Policy.WrapAsync(httpRequestFallbackPolicy, httpRetryPolicy);
20
21builder.Services.AddHttpClient("InventoryApi", client =>
22{
23    client.BaseAddress = new Uri("http://localhost:5000/");
24    client.DefaultRequestHeaders.Add("Accept", "application/json");
25}).AddPolicyHandler(retryAndFallbackWrap);
26
27var app = builder.Build();
28
29// Endpoint that fails 100% of the time
30int requestCount = 0;
31
32app.MapGet("/Inventory/{id}", (int id) =>
33{
34    Console.WriteLine($"{++requestCount} Something went wrong");
35    return Results.Problem("Something went wrong");
36});
37
38
39// Endpoint takes a Http Client Factory with Polly Wrap 
40app.MapGet("/Catalog/{id}", async (int id, IHttpClientFactory httpClientFactory) =>
41{
42    var httpClient = httpClientFactory.CreateClient("InventoryApi");
43
44    string requestEndpoint = $"Inventory/{id}";
45
46    HttpResponseMessage response = await httpClient.GetAsync(requestEndpoint);
47
48    if (response.IsSuccessStatusCode)
49    {
50        int itemsInStock = await response.Content.ReadFromJsonAsync<int>();
51        return Results.Ok(itemsInStock);
52    }
53    return Results.Problem("Something went calling the inventory");
54});
55
56app.Run();
  • Lines 7-9 create a Wait and Retry Policy that retries up to three times.
  • Lines 11-16 create the fallback Policy that returns an OK HttpResponseMessage with a content of “-1”.
  • Lines 18-19 create the Policy Wrap that wraps the Fallback Policy around the Wait and Retry Policy.
  • Lines 21-25 create a HttpClientFactory, and adds the Policy Wrap to it.
  • Lines 32-36 create an endpoint that fails 100% of the time.
  • Lines 40-54 create an endpoint that takes HttpClientFactory as a parameter, creates HttpClient, makes a Http request that executes inside the Policy Wrap.

Hope that helps!

comments powered by Disqus

Related