Polly with .NET 6, Part 2 - Dependency Injection of a HttpClientFactory with a Retry Policy

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 and working with the HttpClientFactory.

Add the Polly NuGet package to you project -

dotnet add package Polly

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

using Polly;

Add the HttpClientFactory 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)
    );

Those are all the changes needed.

Accessing the HttpClientFactory in the controller has not changed, it is passed in via the constructor and used as you would in earlier versions of .NET -

public class CatalogController : ControllerBase
{
    private readonly IHttpClientFactory _httpClientFactory;
    public CatalogController(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> Get(int id)
    {
        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 Ok(itemsInStock);
        }

        return StatusCode((int)response.StatusCode, response.Content.ReadAsStringAsync());
    }
}

Download full source code.

comments powered by Disqus

Related