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

SerializingCacheProvider<TResult, TSerialized>

public class SerializingCacheProvider<TResult, TSerialized> : ISyncCacheProvider<TResult>
Defines an ISyncCacheProvider<T> which serializes objects of type TResult in and out of an underlying cache which caches as type TSerialized. For use with synchronous CachePolicy.
using System; using System.Runtime.CompilerServices; namespace Polly.Caching { [System.Runtime.CompilerServices.NullableContext(1)] [System.Runtime.CompilerServices.Nullable(0)] public class SerializingCacheProvider<[System.Runtime.CompilerServices.Nullable(2)] TResult, [System.Runtime.CompilerServices.Nullable(2)] TSerialized> : ISyncCacheProvider<TResult> { private readonly ISyncCacheProvider<TSerialized> _wrappedCacheProvider; private readonly ICacheItemSerializer<TResult, TSerialized> _serializer; public SerializingCacheProvider(ISyncCacheProvider<TSerialized> wrappedCacheProvider, ICacheItemSerializer<TResult, TSerialized> serializer) { if (wrappedCacheProvider == null) throw new ArgumentNullException("wrappedCacheProvider"); _wrappedCacheProvider = wrappedCacheProvider; if (serializer == null) throw new ArgumentNullException("serializer"); _serializer = serializer; } [return: System.Runtime.CompilerServices.Nullable(new byte[] { 0, 2 })] public (bool, TResult) TryGet(string key) { (bool, TSerialized) valueTuple = _wrappedCacheProvider.TryGet(key); bool item = valueTuple.Item1; TSerialized item2 = valueTuple.Item2; return (item, item ? _serializer.Deserialize(item2) : default(TResult)); } public void Put(string key, [System.Runtime.CompilerServices.Nullable(2)] TResult value, Ttl ttl) { _wrappedCacheProvider.Put(key, _serializer.Serialize(value), ttl); } } }