Polly with .NET 6, Part 4 - Dependency Injection of a HttpClientFactory and Policy into a Minimal API Endpoint

Download full source code.

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

If you are using .NET 6 with the traditional Startup.cs and Program.cs, you don’t need to change anything about how you are using Polly. It all works the same.

But if you are using the new “top-level” statements and minimal API, it’s all very different.

Add Package and Using

Add the Polly NuGet package to you project -

dotnet add package Polly

In Program.cs add a using statement at the top -

using Polly;

HttpClientFactory, Policy and DI container

Create the HttpClientFactory with a retry policy, and add it to the service collection -

builder.Services.AddHttpClient("InventoryApi", client =>
{
    client.BaseAddress = new Uri("http://localhost:5000/");
    client.DefaultRequestHeaders.Add("Accept", "application/json");
}).AddPolicyHandler(Policy.HandleResult<HttpResponseMessage>
 (r => !r.IsSuccessStatusCode).RetryAsync(3));

var app = builder.Build();

Endpoints and DI

Create an endpoint that returns errors 75% of the time -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
int _requestCount = 0; 

app.MapGet("/Inventory/{id}", (int id) =>
{
    _requestCount++;

    if (_requestCount % 4 == 0) // only one of out four requests will succeed
    {
        System.Console.WriteLine($"{_requestCount} It worked!");
        return Results.Ok(15);
    }

    System.Console.WriteLine($"{_requestCount} Something went wrong");
    return Results.Problem("Something went wrong");
});

Add an endpoint that takes the HttpClientFactory by DI -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
app.MapGet("/Catalog/{id}", async (int id, IHttpClientFactory httpClientFactory) =>
{
    var httpClient = httpClientFactory.CreateClient("InventoryApi");

    string requestEndpoint = $"Inventory/{id}";

    HttpResponseMessage response = await httpClient.GetAsync(requestEndpoint);

    if (response.IsSuccessStatusCode)
    {
        int itemsInStock = await response.Content.ReadFromJsonAsync<int>();
        return Results.Ok(itemsInStock);
    }
    return Results.Problem("Something went wrong");

});

Start the application, and hit http://localhost:5000/catalog/1. You will see console statements showing the retries.

That’s it!

Download full source code.

comments powered by Disqus

Related