My service definition:
var host = new HostBuilder().ConfigureServices(services =>
{
services
.AddHttpClient<Downloader>()
.AddPolicyHandler((services, request) =>
HttpPolicyExtensions
.HandleTransientHttpError()
.Or<SocketException>()
.Or<HttpRequestException>()
.WaitAndRetryAsync(
new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10) },
onRetry: (outcome, timespan, retryAttempt, context) =>
{
Console.WriteLine($"Delaying {timespan}, retrying {retryAttempt}.");
}));
services.AddTransient<Downloader>();
}).Build();
Implementation of the Downloader
:
class Downloader
{
private HttpClient _client;
public Downloader(IHttpClientFactory factory)
{
_client = factory.CreateClient();
}
public Download()
{
await _client.GetAsync(new Uri("localhost:8800")); // A port that no application is listening
}
}
With this setup, I expect to see three attempts of querying the endpoint, with the logging message printed to the console (I've also unsuccessfully tried with a logger, using the console for simplicity here).
Instead of the debugging messages, I see the unhandled exception message (which I only expect to see after the retries and the printed logs).
Unhandled exception: System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it. (127.0.0.1:8800) ---> System.Net.Sockets.SocketException (10061): No connection could be made because the target machine actively refused it.
600
seconds and increased the client's timeout accordingly) that obviously will be a noticeable wait; I did not notice that long wait! :) It quickly throws the exception on the console and exits. – Malnourishedservices.AddTransient<Downloader>();
it seems if it is kept, the instance will get a different client than the one configured with poly (stevejgordon.co.uk/…), also changingDownloader(IHttpClientFactory
toDownloader(HttpClient
fixes the issue. I am a bit confused since most examples on MSFT docs use client factory. Though I'm happy to proven wrong and shown the error is somewhere else. – Malnourished