/PlayingWithHttpClientFactory

Try out the built-in HttpClientFactory in ASP.NET Core WebAPI, using Polly to retry.

Primary LanguageC#

Playing with HttpClientFactory

This small application is an example to use the built-in HttpClientFactory in ASP.NET Core.

Separate branch with the .NET Core 2.2 version.

What is HttpClientFactory?

  • HttpClientFactory provides a central location to configure and create HttpClient instances.

Resources

Unit Test for mocking HttpClient

Polly

  • Using Polly as a resilience and transient-fault-handling library, which can helps you to easily write retry logic. Other useful information: Polly and HttpClientFactory.

  • In the example, I use a timeout policy to cancel a long running call. You can find a solution to use CancellationToken in case, if the client side application cancel the request.

You can find a similar example in this repository: Playing with Refit. Automatic type-safe REST library to initiate http calls.

In the example, I did not use the Flurl as fluent URL builder and HTTP client library. Worth to check the following article: Consuming GitHub API (REST) With Flurl.

ConfigureServices in action

public void ConfigureServices(IServiceCollection services)
{
  // Add: MessageHandler(s) to the DI container.
  services.AddTransient<TestMessageHandler>();

  // Create: Polly policy
  AsyncRetryPolicy<HttpResponseMessage> retryPolicy = HttpPolicyExtensions
    .HandleTransientHttpError()
    .Or<TimeoutRejectedException>() // Thrown by Polly's TimeoutPolicy if the inner call gets timeout.
    .WaitAndRetryAsync(_wrc.Retry, _ => TimeSpan.FromMilliseconds(_wrc.Wait));

  AsyncTimeoutPolicy<HttpResponseMessage> timeoutPolicy = Policy
    .TimeoutAsync<HttpResponseMessage>(TimeSpan.FromMilliseconds(_wrc.Timeout));

  // Add your service/clients with an interface, helps you to make your business logic testable.
  // --> Add: HttpClient + Polly WaitAndRetry for HTTP 5xx and 408 responses.
  services.AddHttpClient<IUserClient, UserHttpClient>()
    .AddPolicyHandler(retryPolicy)
    .AddPolicyHandler(timeoutPolicy) // The order of adding is imporant!
    // Add: MessageHandler(s).
    .AddHttpMessageHandler<TestMessageHandler>();
}