<PackageReference Include="Polly" Version="8.3.1" />

ContextualTtl

public class ContextualTtl : ITtlStrategy, ITtlStrategy<object>
Defines a ttl strategy which will cache items for a TimeSpan which may be influenced by data in the execution context.
using System; using System.Runtime.CompilerServices; namespace Polly.Caching { [System.Runtime.CompilerServices.NullableContext(1)] [System.Runtime.CompilerServices.Nullable(0)] public class ContextualTtl : ITtlStrategy, ITtlStrategy<object> { public static readonly string TimeSpanKey = "ContextualTtlTimeSpan"; public static readonly string SlidingExpirationKey = "ContextualTtlSliding"; private static readonly Ttl _noTtl = new Ttl(TimeSpan.Zero, false); public Ttl GetTtl(Context context, [System.Runtime.CompilerServices.Nullable(2)] object result) { if (!context.ContainsKey(TimeSpanKey)) return _noTtl; bool slidingExpiration = false; if (context.TryGetValue(SlidingExpirationKey, out object value)) slidingExpiration = (value as bool?).GetValueOrDefault(); return new Ttl((context[TimeSpanKey] as TimeSpan?) ?? TimeSpan.Zero, slidingExpiration); } } }