Polly with .NET 6, Part 3 - Dependency Injection of a 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;

Policy and DI container

Create the policy and add it to the service collection, and create the HttpClient (it will be reused in multiple requests) -

builder.Services.AddSingleton<IAsyncPolicy<HttpResponseMessage>>(Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt)));

HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new System.Uri(@"http://localhost:5000/");

var app = builder.Build();

Endpoints and DI

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

 1int _requestCount = 0; 
 3app.MapGet("/Inventory/{id}", (int id) =>
 5    _requestCount++;
 7    if (_requestCount % 4 == 0) // only one of out four requests will succeed
 8    {
 9        System.Console.WriteLine($"{_requestCount} It worked!");
10        return Results.Ok(15);
11    }
13    System.Console.WriteLine($"{_requestCount} Something went wrong");
14    return Results.Problem("Something went wrong");

Add an endpoint that takes the Polly policy by DI and uses the HttpClient created above -

 1app.MapGet("/Catalog/{id}", async (int id, IAsyncPolicy<HttpResponseMessage> policy) =>
 3    string requestEndpoint = $"Inventory/{id}";
 5    HttpResponseMessage response = await policy.ExecuteAsync(() => httpClient.GetAsync(requestEndpoint));
 7    if (response.IsSuccessStatusCode)
 8    {
 9        int itemsInStock = await response.Content.ReadFromJsonAsync<int>();
10        return Results.Ok(itemsInStock);
11    }
12    return Results.Problem("Something went wrong calling the inventory");

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

That’s it, not too difficult.

Download full source code.

comments powered by Disqus