Quantcast
Channel: Active questions tagged retry-logic - Stack Overflow
Viewing all articles
Browse latest Browse all 950

Leveraging AddStandardResilienceHandler and AddStandardHedgingHandler in .NET 8 for Resiliency

$
0
0

I have a .NET 8 API using Polly for resiliency with external services like Azure SQL and Microsoft Graph. My current implementation uses custom retry and circuit breaker policies as shown below:

PollyExtensions.cs:

public static class PollyExtensions{    public static AsyncRetryPolicy CreateRetryPolicy(this ILogger logger, string infraService)    {        var delay = Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromSeconds(1), retryCount: 5);        return Policy            .Handle<SqlException>()            .Or<Exception>()            .Or<TimeoutException>()            .WaitAndRetryAsync(delay,                onRetry: (exception, timespan, retryAttempt, context) =>                {                    logger.LogWarning(exception, "Error talking to {infraService}, Error: {Message}, will retry after {timeSpan}. Retry attempt {retryCount} ",                        infraService, exception.Message, timespan, retryAttempt);                });    }    public static AsyncCircuitBreakerPolicy CreateCircuitBreakerPolicy()    {        return Policy            .Handle<Exception>()            .CircuitBreakerAsync(                exceptionsAllowedBeforeBreaking: 5,                durationOfBreak: TimeSpan.FromMinutes(1)            );    }}

While exploring new features in .NET 8, I came across AddStandardResilienceHandler and AddStandardHedgingHandler for implementing resiliency.

References :

https://devblogs.microsoft.com/dotnet/building-resilient-cloud-services-with-dotnet-8/

https://juliocasal.com/blog/Building-Microservices-With-Dotnet-8

Can someone provide code samples demonstrating how to use AddStandardResilienceHandler and AddStandardHedgingHandler in the context of my GraphSvcClient class for external dependency calls?

Are there any specific considerations when using these new functionalities compared to custom policies?

GraphSvcClient.cs

public sealed class GraphSvcClient(ICacheProvider cacheProvider,    IAzureAuthTokenService azureAuthTokenService,        ILogger<GraphSvcClient> logger) : IGraphSvcClient{    private readonly ICacheProvider _cacheProvider = cacheProvider.IsNotNull();    private readonly IAzureAuthTokenService _azureAuthTokenService = azureAuthTokenService.IsNotNull();    private readonly ILogger<GraphSvcClient> _logger = logger.IsNotNull();    /// <summary>    /// Get Microsoft Graph graphClient    /// </summary>    /// <returns></returns>    public async Task<GraphServiceClient> GetGraphServiceClientAsync()    {        var accessToken = await GetAccessTokenAsync();        var retryPolicy = _logger.CreateRetryPolicy(infraService: "MicrosoftGraph");        var circuitBreakerPolicy = PollyExtensions.CreateCircuitBreakerPolicy();        var combinedPolicy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy);        var graphServiceClient = await combinedPolicy.ExecuteAsync(async () =>        {            var client = new GraphServiceClient(new DelegateAuthenticationProvider(async (req) =>            {                req.Headers.Authorization = new AuthenticationHeaderValue(JwtBearerDefaults.AuthenticationScheme, accessToken);                await Task.CompletedTask;            }));            return client;        });        return graphServiceClient;    }}

I'm considering updating Polly and its related nuget packages to their latest compatible versions to leverage the latest features in .NET 8.

List of Nuget Packages used in the project :

<PackageReference Include="Polly" Version="7.2.4" /><PackageReference Include="Polly.Contrib.WaitAndRetry" Version="1.1.1" /><PackageReference Include="Microsoft.Extensions.Http.Polly" Version="8.0.0" />

Viewing all articles
Browse latest Browse all 950

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>