Skip to content

Instantly share code, notes, and snippets.

@angelobelchior
Last active September 2, 2019 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angelobelchior/6962fcf3551e586461d85d1297283b40 to your computer and use it in GitHub Desktop.
Save angelobelchior/6962fcf3551e586461d85d1297283b40 to your computer and use it in GitHub Desktop.
public abstract class ServiceBase
{
private readonly HttpClient _httpClient;
private readonly AsyncRetryPolicy _asyncRetryPolicy;
public ServiceBase(HttpClient httpClient, RetryPolicyConfiguration retryPolicyConfiguration)
{
this._httpClient = httpClient;
this._asyncRetryPolicy = this.CreatePolicy(retryPolicyConfiguration);
}
protected async Task<Result<T>> Get<T>(string url)
{
return await this._asyncRetryPolicy.ExecuteAsync(async () =>
{
var response = await this._httpClient.GetAsync(url);
return await this.GetRequestContent<T>(response);
});
}
{...}
private AsyncRetryPolicy CreatePolicy(RetryPolicyConfiguration retryPolicyConfiguration)
=> Policy.Handle<Exception>(e => this.CanContinue(e) /*aqui você verifica, baseado na exception lançada, se deve continuar com o retry ou não */)
.WaitAndRetryAsync(retryCount: retryPolicyConfiguration.RetryCount,
retryAttempt => TimeSpan.FromSeconds(retryAttempt * retryPolicyConfiguration.RetryAttemptFactor)
);
}
public class RetryPolicyConfiguration
{
public static RetryPolicyConfiguration Default = new RetryPolicyConfiguration(3, 1);
public int RetryCount { get; }
public int RetryAttemptFactor { get; }
public RetryPolicyConfiguration(int retryCount, int retryAttemptFactor)
{
this.RetryCount = retryCount;
this.RetryAttemptFactor = retryAttemptFactor;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment