0

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.

Vergil C.
  • 1,046
  • 2
  • 15
  • 28
  • Does this answer your question? [Polly retry with different url](https://stackoverflow.com/questions/62084405/polly-retry-with-different-url) – Peter Csala Feb 15 '21 at 12:40

1 Answers1

0

As covered in other questions, System.Net.Http.HttpClient is not designed for BaseAddress to be changed.

You do not however have to use different HttpClient instances to target URIs with different base addresses. You can simply not set the BaseAddress property on the HttpClient you configure, and use fully-qualified URIs (to switch eg between primary and failover URIs) in the calls you place through a single HttpClient instance.

mountain traveller
  • 7,591
  • 33
  • 38