@@ -6,7 +6,7 @@ namespace Polly.Caching;
6
6
internal sealed class HybridCacheResilienceStrategy < TResult > : ResilienceStrategy < TResult >
7
7
{
8
8
private readonly HybridCache _cache ;
9
- private readonly Func < ResilienceContext , string ? > _keyGen ;
9
+ private readonly Func < ResilienceContext , string ? > _keyGenerator ;
10
10
11
11
public HybridCacheResilienceStrategy ( HybridCacheStrategyOptions < TResult > options )
12
12
{
@@ -17,30 +17,53 @@ public HybridCacheResilienceStrategy(HybridCacheStrategyOptions<TResult> options
17
17
}
18
18
19
19
_cache = options . Cache ;
20
- _keyGen = options . CacheKeyGenerator ?? ( ctx => ctx . OperationKey ) ;
20
+ _keyGenerator = options . CacheKeyGenerator ?? ( static ctx => ctx . OperationKey ) ;
21
21
}
22
22
23
23
protected override async ValueTask < Outcome < TResult > > ExecuteCore < TState > (
24
24
Func < ResilienceContext , TState , ValueTask < Outcome < TResult > > > callback ,
25
25
ResilienceContext context ,
26
26
TState state )
27
27
{
28
- var key = _keyGen ( context ) ;
28
+ var key = _keyGenerator ( context ) ;
29
29
if ( string . IsNullOrEmpty ( key ) )
30
30
{
31
- return await callback ( context , state ) . ConfigureAwait ( context . ContinueOnCapturedContext ) ;
31
+ return Outcome . FromException < TResult > ( new InvalidOperationException ( "HybridCache key was null or empty." ) ) ;
32
32
}
33
33
34
+ var payload = new FactoryState < TState > ( callback , context , state , context . ContinueOnCapturedContext ) ;
35
+
34
36
var result = await _cache . GetOrCreateAsync (
35
- key ! ,
36
- async ct =>
37
+ key ,
38
+ payload ,
39
+ static async ( s , _ ) =>
37
40
{
38
- var outcome = await callback ( context , state ) . ConfigureAwait ( context . ContinueOnCapturedContext ) ;
41
+ var outcome = await s . Callback ( s . Context , s . State ) . ConfigureAwait ( s . ContinueOnCapturedContext ) ;
39
42
outcome . ThrowIfException ( ) ;
40
43
return outcome . Result ! ;
41
44
} ,
42
45
cancellationToken : context . CancellationToken ) . ConfigureAwait ( context . ContinueOnCapturedContext ) ;
43
46
44
47
return Outcome . FromResult ( result ) ;
45
48
}
49
+
50
+ private readonly struct FactoryState < T >
51
+ {
52
+ public FactoryState (
53
+ Func < ResilienceContext , T , ValueTask < Outcome < TResult > > > callback ,
54
+ ResilienceContext context ,
55
+ T state ,
56
+ bool continueOnCapturedContext )
57
+ {
58
+ Callback = callback ;
59
+ Context = context ;
60
+ State = state ;
61
+ ContinueOnCapturedContext = continueOnCapturedContext ;
62
+ }
63
+
64
+ public Func < ResilienceContext , T , ValueTask < Outcome < TResult > > > Callback { get ; }
65
+ public ResilienceContext Context { get ; }
66
+ public T State { get ; }
67
+ public bool ContinueOnCapturedContext { get ; }
68
+ }
46
69
}
0 commit comments