As I am building out my MyReverie( project in GitHub, I wanted to add some resilience to my http calls. I had heard of the Polly framework that made doing this extremely easily.

For my purposes I wanted to simply add an ability that if the endpoint was for some reason unavailable(quite possible working with Microservices) that it would retry a certain number of times and not simply fail after the first attempt. It is a simple use case but it allowed me to easily become familiar with this framework.

To get Polly up and running is quite straight forward. In my service class within my web project where I make my http calls to the API I inject ‘IHttpClientFactory’ using Dependancy Injection which comes out of the box with .Net Core as a constructor parameter.

I then assign this parameter to a local variable ‘_httpClientFactory’ in the constructor as below

In the startup class I define the http client

This effectively means to retry the http call five time before returning with a failure response. I chose 5 as a reasonable amount of times to retry but you can choose whichever number you wish.

I need to of course add the package:

in my case I am using v2.2.0

then add the using statement

I then initialize a new HttpClient object to a the defined client in the startup class by

after which I use to make the http calls as you would normally do, but this time incorporating Polly as a resilience mechanism. In my case it is:

That’s’ it.

Leave a Reply

Notify of