/PlayingWithRefit

Try out the Refit, automatic type-safe REST library in ASP.NET Core WebAPI, using Polly to retry.

Primary LanguageC#

Playing with Refit

This small WebAPI is an example of using Refit, an automatic type-safe REST library. This concept can be beneficial for initiating calls to 3rd-party services.

Resources

Polly and Refit hand in hand

  • With Refit, you can use Polly as a resilience and transient-fault-handling library, which can helps you to easily write retry logic.
  • Using Polly with HttpClient factory 👤
  • In the example, I use a timeout policy to cancel a long-running call. You can find a solution for using CancellationToken in case the client-side application cancels the request.
Alternatives

In my Playing with HttpClientFactory, I used the built-in HttpClientFactory to initiate http calls.

ConfigureServices in action

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

    // --> 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: RefitClient.
    services.AddRefitClient<IUserClient>()
        .ConfigureHttpClient(c => c.BaseAddress = new Uri("http://localhost:5000"))
        .AddPolicyHandler(retryPolicy)
        .AddPolicyHandler(timeoutPolicy) // The order of adding is imporant!
        .AddHttpMessageHandler<AuthorizationMessageHandler>();
}