Polly with .NET 6, Part 1 - Dependency Injection of a Policy into a Controller
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, there are some minor changes needed to handle the new way of accessing the service collection container.
Add the Polly NuGet package to you project -
dotnet add package Polly
In Program.cs
add a using statement at the top -
using Polly;
Create the policy -
var httpRetryPolicy = Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt));
Add the policy to the service collection -
builder.Services.AddSingleton<IAsyncPolicy<HttpResponseMessage>>(httpRetryPolicy);
Those are all the changes needed.
Accessing the policy in the controller has not changed, so I won’t include it here, but the attached zip has a full example.
Download full source code.