ContextualTtl
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 == null)
throw new ArgumentNullException("context");
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);
}
}
}