Reusing Polly Policies with Dependency Injection

Download full source code.

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

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

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 -

 1public class Policies
 3    public readonly RetryPolicy<HttpResponseMessage> InternalServerErrorPolicy;
 4    public readonly RetryPolicy<HttpResponseMessage> RequestTimeoutPolicy;
 5    public Policies()
 6    {
 7        InternalServerErrorPolicy = Policy.HandleResult<HttpResponseMessage>(
 8           r => r.StatusCode == HttpStatusCode.InternalServerError)
 9       .WaitAndRetryAsync(3,
10           retryAttempt => TimeSpan.FromSeconds(retryAttempt));
12        RequestTimeoutPolicy = Policy.HandleResult<HttpResponseMessage>(
13            r => r.StatusCode == HttpStatusCode.RequestTimeout)
14        .WaitAndRetryAsync(3, 
15            retryAttempt => TimeSpan.FromSeconds(Math.Pow(0.2, retryAttempt)));
16    }

Then my DI class I register the Policies.

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

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

1public class ItemsController : ApiController
3    private readonly Policies _policies;
4    public ItemsController(Policies policies)
5    {
6        _policies = policies;
7    }

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

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


HttpResponseMessage httpResponse = 
  await _policies.RequestTimeoutPolicy.ExecuteAsync(
     () => httpClient.GetAsync(requestEndpoint));
That’s it.

Download full source code.

comments powered by Disqus