Skip to content

Instantly share code, notes, and snippets.

@alefcarlos
Last active January 12, 2019 07:27
Show Gist options
  • Save alefcarlos/f25c47949d6ac4826800a6bf6360b64b to your computer and use it in GitHub Desktop.
Save alefcarlos/f25c47949d6ac4826800a6bf6360b64b to your computer and use it in GitHub Desktop.
public override void ConfigureServices(IServiceCollection services)
{
//Configurando policy de timeout padrão
var timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(10);
//Add services
services.AddHttpClient<ApiService>()
.AddPolicyHandler(GetRetryPolicy())
.AddPolicyHandler(timeoutPolicy);
//Add Host services
services.AddHostedService<HandlerHosted>();
}
/// <summary>
/// É adicionado uma política para tentar 3 vezes com uma repetição exponencial, começando em um segundo.
/// </summary>
/// <returns></returns>
static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.Unauthorized)
.Or<TimeoutRejectedException>()
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(1, retryAttempt)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment