I have implemented Polly in my solution using .net core 3.1 and Polly 7.2.0. I have created extensions for IServiceCollection and in my Startup file I am calling the extensions to configure and add a client and also to create a policy and and register it.
In my ExternalClient class, I am using the IHttpClientFactory to consume my client and IAsyncPolicy policy to wrap my calls with the policy I have created and set up on my Startup.
Startup.cs
...
services.AddHttpClients(Configuration);
services.AddRetryPolicy(Configuration);
...
ServiceCollectionExtension.cs
...
var policy = Policy
.Handle<HttpRequestException>()
.WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(retryCount), (exception, timeSpan, count,
context) =>
{
LogTo.Error($"Failed while posting to {myClient.Host}, retrying: " +
$"{count} of {retryCount} in " +
$"{timeSpan.TotalSeconds} seconds, with exception " +
$"{exception.Message}");
});
services.AddHttpClient("MyClient", c => { c.BaseAddress = new Uri(myClient.Host); })
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
Credentials = credentialsCache
});
...
ExternalClient
...
try
{
var response = await _policy
.ExecuteAsync(async () => (await _client.PostAsync(endpoint, requestBody)).EnsureSuccessStatusCode())
.ConfigureAwait(false);
return response.StatusCode == HttpStatusCode.OK;
}
catch (Exception ex)
{
LogTo.Error(ex, "Unable to contact Myclient");
}
...
The implementation of the policy works fine, the next step is to examine is there is a way to add a failover url for my client. I have checked the documentation for Polly and also have seen this approach with WebClient but this would work if the policy and the implementation are in the same place. I believe it would be possible to do it if I have the http client call happen in a method where I can wrap the call to that with ExecuteAsync and then supply diffent client but I was looking a more elegant solution, something that maybe out there but I am not aware of.