Polly, HttpClientFactory and the Policy Registry - choosing the right policy based on the HTTP request

Full source code available here.

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

The release of .NET Core 2.1 has made using HttpClient much easier. If you have been using HttpClient for a while you will know about its limitations around reuse and DNS expiry, I wrote about this some time ago. The HttpClientFactory takes care of the problems addressed in that post.

Along with those improvements the HttpClientFactory now makes it very easy to add Polly policies that will be executed whenever you create a HttpClient with the factory. This means you define the polices in one place, add them to the factory and forget about them! No more code is needed to add resilience to each of your calls. The factory takes care of creating the client and applying the policy, you can’t even tell that Polly is protecting your call where you make it.

For more on the HttpClientFactory check out Steve Gordon’s series of articles.

A simple example

Here’s a simple example of the HttpClientFactory in use. This adds the factory to our dependency injection container, sets the base address of the remote server and lets us configure the client. It also adds a simple retry policy that checks if the response is NOT a success code and retries up to three times.

1services.AddHttpClient("OrderApiServer", client =>
3    client.BaseAddress = new Uri("http://localhost:57696/api/");
4    client.DefaultRequestHeaders.Add("Accept", "application/json");
6    (r => !r.IsSuccessStatusCode).RetryAsync(3));

When you create a HttpClient now, it will include the policy.

var httpClient = _httpClientFactory.CreateClient("OrderApiServer");
And when you execute a request it the policy will retry up to three times if necessary.

var result = await httpClient.GetAsync("api/SomeEndpoint);

This might be great if all you are going to is perform GET’s and every call you make is safe and idempotent. But what if you want to use GET, PUT, POST and DELETE, you won’t want to retry all of those requests?

This is easy too. You add a policy registry will all the policies you want to use. Say, a retry policy, a wait and retry policy and no op policy, and provide a selector method to pick the right one based on the HTTP verb (or even the endpoint you are requesting).

Using a Policy Registry with the HttpClientFactory

Step 1

Add the policy registry to the Service Collection and add the policies to the registry.

 1public void ConfigureServices(IServiceCollection services)
 3    IPolicyRegistry<string> registry = services.AddPolicyRegistry(); // creates the registry and adds it to the service collection
 5    IAsyncPolicy<HttpResponseMessage> httpRetryPolicy =
 6        Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
 7            .RetryAsync(3);
 9    registry.Add("SimpleHttpRetryPolicy", httpRetryPolicy);
11    IAsyncPolicy<HttpResponseMessage> httWaitAndpRetryPolicy =
12        Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
13            .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt));
15    registry.Add("SimpleWaitAndRetryPolicy", httWaitAndpRetryPolicy);
17    IAsyncPolicy<HttpResponseMessage> noOpPolicy = Policy.NoOpAsync()
18        .AsAsyncPolicy<HttpResponseMessage>();
20    registry.Add("NoOpPolicy", noOpPolicy);
21    //snip..

Step 2

Now that we have the three polices and the registry, lets add the HttpClientFactory to the Service Collection.

1services.AddHttpClient("OrderApiServer", client =>
3    client.BaseAddress = new Uri("http://localhost:57696/api/");
4    client.DefaultRequestHeaders.Add("Accept", "application/json");

Note the PolicySelector, this is the method I use to choose the right policy for each request.

Step 3

This method is simple, it takes the registry and the HttpRequest as arguments and grabs the policy from the registry based on the HTTP verb.

 1private IAsyncPolicy<HttpResponseMessage> PolicySelector(IReadOnlyPolicyRegistry<string> policyRegistry, HttpRequestMessage httpRequestMessage)
 3    if (httpRequestMessage.Method == HttpMethod.Get)
 4    {
 5        return policyRegistry.Get<IAsyncPolicy<HttpResponseMessage>>("SimpleHttpRetryPolicy");
 6    }
 7    else if (httpRequestMessage.Method == HttpMethod.Post)
 8    {
 9        return policyRegistry.Get<IAsyncPolicy<HttpResponseMessage>>("NoOpPolicy");
10    }
11    else
12    {
13        return policyRegistry.Get<IAsyncPolicy<HttpResponseMessage>>("SimpleWaitAndRetryPolicy");
14    }

You could use a lambda instead of a method when creating the HttpClientFactory. For example if if you had two policies to choose from -

.AddPolicyHandlerFromRegistry((policyRegistry, message) => policyRegistry.Get<IAsyncPolicy<HttpResponseMessage>>(message.Method == HttpMethod.Get ? "SimpleHttpRetryPolicy" : "NoOpPolicy"));

That’s the hard work done.

Step 4

Let’s take a look at the controller.

 1public class OrderController : ControllerBase
 3    private readonly IHttpClientFactory _httpClientFactory;
 5    public OrderController(IHttpClientFactory httpClientFactory)
 6    {
 7        _httpClientFactory = httpClientFactory;
 8    }
10    [HttpGet("{orderId}")]
11    public async Task<ActionResult> Get(int orderId)
12    {
13        //snip
14        string requestEndpoint = $"invoice/{orderId}";
16        var httpClient = _httpClientFactory.CreateClient("OrderApiServer");
18        HttpResponseMessage response = await httpClient.GetAsync(requestEndpoint);
20		//handle response
21    }	

The only thing I’m passing into the constructor is the HttpClientFactory, I don’t have any Polly using statements.

In the GET method you can’t even tell that there is a policy around the HttpClient.GetAsync(..)

All the Polly work is done in the Startup.cs, the policies are defined, added to the registry, the registry is added to the HttpClientFactory and the HttpClientFactory is added to the services collections.

Now all your HttpClient requests are executed inside a policy.

For more on this, check out Dylan’s Polly and HttpClientFactory documentation.

Full source code available here.

comments powered by Disqus