Reusing Polly Policies with Dependency Injection

Download full source code.

In my previous post “A simple Polly example with WebApi 2” I showed how to make a request to an unreliable endpoint protected by a Polly retry policy. For more on Polly see www.thepollyproject.org.

In that example I created the Polly policy in the constructor of the controller. That of course means it was not reusable, I would have to copy that code into all other controllers that needed the policy, and any policy changes would require me to edit all the controllers. Not a good solution.

In this post I’m going to show how to use dependency injection to share and reuse Polly policies.

Using Dependency Injection with Polly

In this example I’m working with ninject, but you you can use any DI that suits you. See here for more info on ninject – “Web API 2 and ninject, how to make them work together”.

I firstly create all my Polly policies in a simple class like so –

public class Policies
{
    public readonly RetryPolicy<HttpResponseMessage> InternalServerErrorPolicy;
    public readonly RetryPolicy<HttpResponseMessage> RequestTimeoutPolicy;
    public Policies()
    {
        InternalServerErrorPolicy = Policy.HandleResult<HttpResponseMessage>(
           r => r.StatusCode == HttpStatusCode.InternalServerError)
       .WaitAndRetryAsync(3,
           retryAttempt => TimeSpan.FromSeconds(retryAttempt));

        RequestTimeoutPolicy = Policy.HandleResult<HttpResponseMessage>(
            r => r.StatusCode == HttpStatusCode.RequestTimeout)
        .WaitAndRetryAsync(3, 
            retryAttempt => TimeSpan.FromSeconds(Math.Pow(0.2, retryAttempt)));
    }
}

Then my DI class I register the Policies.

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<Policies>().ToSelf().InSingletonScope();
}

My controllers take Policies as a constructor parameter, which ninject provides.

public class ItemsController : ApiController
{
    private readonly Policies _policies;
    public ItemsController(Policies policies)
    {
        _policies = policies;
    }
//snip...

The action methods call other controllers wrapped by one of the policies.

HttpResponseMessage httpResponse =
  await _policies.InternalServerErrorPolicy.ExecuteAsync(
     () => httpClient.GetAsync(requestEndpoint));

and

HttpResponseMessage httpResponse = 
  await _policies.RequestTimeoutPolicy.ExecuteAsync(
     () => httpClient.GetAsync(requestEndpoint));

That’s it.

Download full source code.

A simple Polly example with WebApi 2

Download full source code.

If you are calling APIs and you haven’t heard about The Polly Project, you should check it out. It helps take care of many common problems like unreliable connections, retries and circuit breaking. It can also be used to wrap code where other forms of transient exception may occur.

In this blog post I’m going to show the wait and retry policy when calling an unreliable Web Api endpoint.

When using Polly there are two pieces that need you need to code – the policy and the execution of code wrapped by the policy.

In this example the policy is created in the constructor of the controller, this is NOT what you should do in a real application. For an example using DI to share policies see “Reusing Polly Policies with Dependency Injection”.

readonly RetryPolicy<HttpResponseMessage> _httpRequestPolicy;

public ValuesController()
{
    _httpRequestPolicy = Policy.HandleResult<HttpResponseMessage>(
            r => r.StatusCode == HttpStatusCode.InternalServerError)
        .WaitAndRetryAsync(3,
            retryAttempt => TimeSpan.FromSeconds(retryAttempt));
}

This policy states that in the event that a HttpResponseMessage has a of InternalServerError, the request should be tried up to three times with a back off increasing by one second each time.

That’s the policy in place, now we need to call the web service endpoint.

public async Task<IHttpActionResult> Get()
{
   var httpClient = GetHttpClient();
   string requestEndpoint = "numbers/"; // numbers is the name of the controller being called

   HttpResponseMessage httpResponse = await _httpRequestPolicy.ExecuteAsync(() => httpClient.GetAsync(requestEndpoint));

   IEnumerable<int> numbers = await httpResponse.Content.ReadAsAsync<IEnumerable<int>>();
   
   return Ok(numbers);
}

If you execute the code it makes a GET request to http://localhost:2351/api/values, despite two failures when calling the NumbersController you will get a 200 response and a list of numbers.

If you want to verify this, step through the provided solution with the debugger. You’ll see that the first two requests to the NumbersContoller return 500 errors and that the third succeeds and returns an array of ints.

With just a few lines of code Polly provided us with a robust wait and retry mechanism for web requests.

In another blog I’ll show a better way of defining policies so they can be used in any controller.

Download full source code.