Skip to content

Commit edb1ffb

Browse files
authored
Adopt Alpha 2 in samples (#1338)
1 parent c6d386a commit edb1ffb

File tree

7 files changed

+68
-89
lines changed

7 files changed

+68
-89
lines changed

Directory.Packages.props

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<Project>
22
<PropertyGroup>
33
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
4-
<PollyVersion>8.0.0-alpha.1</PollyVersion>
4+
<PollyVersion>8.0.0-alpha.2</PollyVersion>
55
</PropertyGroup>
66
<ItemGroup>
77
<PackageVersion Include="coverlet.msbuild" Version="6.0.0" />

samples/DependencyInjection/Program.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
// You can also register result-based (generic) resilience strategies
2222
// First generic parameter is the key type, the second one is the result type
2323
// This overload does not use the context argument (simple scenarios)
24-
.AddResilienceStrategy<string, HttpResponseMessage>("my-strategy", builder =>
24+
.AddResilienceStrategy<string, HttpResponseMessage>("my-http-strategy", builder =>
2525
{
2626
builder.AddTimeout(TimeSpan.FromSeconds(1));
2727
})
@@ -35,10 +35,10 @@
3535
ResilienceStrategyProvider<string> strategyProvider = serviceProvider.GetRequiredService<ResilienceStrategyProvider<string>>();
3636

3737
// Retrieve the strategy by name
38-
ResilienceStrategy strategy = strategyProvider.Get("my-strategy");
38+
ResilienceStrategy strategy = strategyProvider.GetStrategy("my-strategy");
3939

4040
// Retrieve the generic strategy by name
41-
ResilienceStrategy<HttpResponseMessage> genericStrategy = strategyProvider.Get<HttpResponseMessage>("my-strategy");
41+
ResilienceStrategy<HttpResponseMessage> genericStrategy = strategyProvider.GetStrategy<HttpResponseMessage>("my-http-strategy");
4242

4343
try
4444
{

samples/Extensibility/Program.cs

+2-7
Original file line numberDiff line numberDiff line change
@@ -118,18 +118,13 @@ protected override async ValueTask<Outcome<TResult>> ExecuteCoreAsync<TResult, T
118118
public static class MyResilienceStrategyExtensions
119119
{
120120
// Add new extension that works for both "ResilienceStrategyBuilder" and "ResilienceStrategyBuilder<T>"
121-
public static TBuilder AddMyResilienceStrategy<TBuilder>(this TBuilder builder, MyResilienceStrategyOptions options)
122-
where TBuilder : ResilienceStrategyBuilderBase
123-
{
124-
builder.AddStrategy(
121+
public static TBuilder AddMyResilienceStrategy<TBuilder>(this TBuilder builder, MyResilienceStrategyOptions options) where TBuilder : ResilienceStrategyBuilderBase
122+
=> builder.AddStrategy(
125123
// Provide a factory that creates the strategy
126124
context => new MyResilienceStrategy(context.Telemetry, options),
127125

128126
// Pass the options, note that the options instance is automatically validated by the builder
129127
options);
130-
131-
return builder;
132-
}
133128
}
134129

135130

samples/GenericStrategies/Program.cs

+6-20
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,10 @@
1414
ResilienceStrategy<HttpResponseMessage> strategy = new ResilienceStrategyBuilder<HttpResponseMessage>()
1515
.AddFallback(new FallbackStrategyOptions<HttpResponseMessage>
1616
{
17-
FallbackAction = async _ =>
17+
FallbackAction = _ =>
1818
{
19-
await Task.Delay(10);
20-
2119
// Return fallback result
22-
return new Outcome<HttpResponseMessage>(new HttpResponseMessage(System.Net.HttpStatusCode.OK));
20+
return Outcome.FromResultAsTask(new HttpResponseMessage(HttpStatusCode.OK));
2321
},
2422
// You can also use switch expressions for succinct syntax
2523
ShouldHandle = outcome => outcome switch
@@ -33,22 +31,10 @@
3331
})
3432
.AddRetry(new RetryStrategyOptions<HttpResponseMessage>
3533
{
36-
ShouldRetry = outcome =>
37-
{
38-
// We can handle specific result
39-
if (outcome.Result?.StatusCode == HttpStatusCode.InternalServerError)
40-
{
41-
return PredicateResult.True;
42-
}
43-
44-
// Or exception
45-
if ( outcome.Exception is HttpRequestException)
46-
{
47-
return PredicateResult.True;
48-
}
49-
50-
return PredicateResult.False;
51-
},
34+
// You can use "PredicateBuilder" to configure the predicates
35+
ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
36+
.HandleResult(r => r.StatusCode == HttpStatusCode.InternalServerError)
37+
.Handle<HttpRequestException>(),
5238
// Register user callback called whenever retry occurs
5339
OnRetry = outcome => { Console.WriteLine($"Retrying '{outcome.Result?.StatusCode}'..."); return default; },
5440
BaseDelay = TimeSpan.FromMilliseconds(400),

samples/Intro/Program.cs

+6-9
Original file line numberDiff line numberDiff line change
@@ -41,16 +41,14 @@
4141
// Add retries using the options
4242
.AddRetry(new RetryStrategyOptions
4343
{
44-
ShouldRetry = outcome =>
44+
// To configure the predicate you can use switch expressions
45+
ShouldHandle = args => args.Exception switch
4546
{
46-
// We want to retry on this specific exception
47-
if (outcome.Exception is TimeoutRejectedException)
48-
{
49-
// The "PredicateResult.True" is shorthand to "new ValueTask<bool>(true)"
50-
return PredicateResult.True;
51-
}
47+
TimeoutRejectedException => PredicateResult.True,
5248

53-
return PredicateResult.False;
49+
// The "PredicateResult.False" is just shorthand for "new ValueTask<bool>(true)"
50+
// You can also use "new PredicateBuilder().Handle<TimeoutRejectedException>()"
51+
_ => PredicateResult.False
5452
},
5553
// Register user callback called whenever retry occurs
5654
OnRetry = args => { Console.WriteLine($"Retrying...{args.Arguments.Attempt} attempt"); return default; },
@@ -65,7 +63,6 @@
6563
// Register user callback called whenever timeout occurs
6664
OnTimeout = args =>
6765
{
68-
6966
Console.WriteLine($"Timeout occurred after {args.Timeout}!");
7067
return default;
7168
}

samples/Retries/ExecuteHelper.cs

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using System.Net;
2+
3+
namespace Retries;
4+
5+
internal class ExecuteHelper
6+
{
7+
public bool Fail { get; set; } = true;
8+
9+
public HttpResponseMessage ExecuteUnstable()
10+
{
11+
if (Fail)
12+
{
13+
Fail = false;
14+
Console.WriteLine($"{DateTime.UtcNow}: Execute failed");
15+
throw new InvalidOperationException();
16+
}
17+
18+
Fail = true;
19+
Console.WriteLine($"{DateTime.UtcNow}: Executed");
20+
return new HttpResponseMessage(HttpStatusCode.OK);
21+
}
22+
}

samples/Retries/Program.cs

+28-49
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,31 @@
11
using Polly;
22
using Polly.Retry;
3+
using Retries;
34
using System.Net;
45

6+
var helper = new ExecuteHelper();
7+
58
// ------------------------------------------------------------------------
6-
// 1. Create a retry strategy that only handles invalid operation exceptions
9+
// 1. Create a retry strategy that handles all exceptions
710
// ------------------------------------------------------------------------
811

912
ResilienceStrategy strategy = new ResilienceStrategyBuilder()
10-
.AddRetry(new RetryStrategyOptions
11-
{
12-
// Specify what exceptions should be retried
13-
ShouldRetry = outcome =>
14-
{
15-
if (outcome.Exception is InvalidOperationException)
16-
{
17-
return PredicateResult.True;
18-
}
19-
20-
return PredicateResult.False;
21-
},
22-
})
13+
// Default retry options handle all exceptions
14+
.AddRetry(new RetryStrategyOptions())
2315
.Build();
2416

17+
Console.WriteLine("---------------------------------------");
18+
strategy.Execute(helper.ExecuteUnstable);
19+
2520
// ------------------------------------------------------------------------
2621
// 2. Customize the retry behavior
2722
// ------------------------------------------------------------------------
2823

2924
strategy = new ResilienceStrategyBuilder()
3025
.AddRetry(new RetryStrategyOptions
3126
{
32-
// Specify what exceptions should be retried
33-
ShouldRetry = outcome =>
34-
{
35-
if (outcome.Exception is InvalidOperationException)
36-
{
37-
return PredicateResult.True;
38-
}
39-
40-
return PredicateResult.False;
41-
},
27+
// Specify what exceptions should be retried using PredicateBuilder
28+
ShouldHandle = new PredicateBuilder().Handle<InvalidOperationException>(),
4229
RetryCount = 4,
4330
BaseDelay = TimeSpan.FromSeconds(1),
4431

@@ -48,24 +35,22 @@
4835
})
4936
.Build();
5037

38+
Console.WriteLine("---------------------------------------");
39+
strategy.Execute(helper.ExecuteUnstable);
40+
5141
// ------------------------------------------------------------------------
5242
// 3. Register the callbacks
5343
// ------------------------------------------------------------------------
5444

5545
strategy = new ResilienceStrategyBuilder()
5646
.AddRetry(new RetryStrategyOptions
5747
{
58-
// Specify what exceptions should be retried
59-
ShouldRetry = outcome =>
48+
// Specify what exceptions should be retried using switch expressions
49+
ShouldHandle = args => args.Exception switch
6050
{
61-
if (outcome.Exception is InvalidOperationException)
62-
{
63-
return PredicateResult.True;
64-
}
65-
66-
return PredicateResult.False;
51+
InvalidOperationException => PredicateResult.True,
52+
_ => PredicateResult.False,
6753
},
68-
6954
OnRetry = outcome =>
7055
{
7156
Console.WriteLine($"Retrying attempt {outcome.Arguments.Attempt}...");
@@ -74,6 +59,9 @@
7459
})
7560
.Build();
7661

62+
Console.WriteLine("---------------------------------------");
63+
strategy.Execute(helper.ExecuteUnstable);
64+
7765
// ------------------------------------------------------------------------
7866
// 4. Create an HTTP retry strategy that handles both exceptions and results
7967
// ------------------------------------------------------------------------
@@ -82,22 +70,10 @@
8270
.AddRetry(new RetryStrategyOptions<HttpResponseMessage>
8371
{
8472
// Specify what exceptions or results should be retried
85-
ShouldRetry = outcome =>
86-
{
87-
// Now, also handle results
88-
if (outcome.Result?.StatusCode == HttpStatusCode.InternalServerError)
89-
{
90-
return PredicateResult.True;
91-
}
92-
93-
if (outcome.Exception is InvalidOperationException)
94-
{
95-
return PredicateResult.True;
96-
}
97-
98-
return PredicateResult.False;
99-
},
100-
73+
ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
74+
.Handle<HttpRequestException>()
75+
.Handle<InvalidOperationException>()
76+
.HandleResult(r=>r.StatusCode == HttpStatusCode.InternalServerError),
10177
// Specify delay generator
10278
RetryDelayGenerator = outcome =>
10379
{
@@ -112,3 +88,6 @@
11288
}
11389
})
11490
.Build();
91+
92+
Console.WriteLine("---------------------------------------");
93+
httpStrategy.Execute(helper.ExecuteUnstable);

0 commit comments

Comments
 (0)