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

AsyncSerializingCacheProvider<TResult, TSerialized>

public class AsyncSerializingCacheProvider<TResult, TSerialized> : IAsyncCacheProvider<TResult>
Defines an IAsyncCacheProvider<T> which serializes objects of type TResult in and out of an underlying cache which caches as type TSerialized. For use with asynchronous CachePolicy.
using System; using System.Threading; using System.Threading.Tasks; namespace Polly.Caching { public class AsyncSerializingCacheProvider<TResult, TSerialized> : IAsyncCacheProvider<TResult> { private readonly IAsyncCacheProvider<TSerialized> _wrappedCacheProvider; private readonly ICacheItemSerializer<TResult, TSerialized> _serializer; public AsyncSerializingCacheProvider(IAsyncCacheProvider<TSerialized> wrappedCacheProvider, ICacheItemSerializer<TResult, TSerialized> serializer) { if (wrappedCacheProvider == null) throw new ArgumentNullException("wrappedCacheProvider"); _wrappedCacheProvider = wrappedCacheProvider; if (serializer == null) throw new ArgumentNullException("serializer"); _serializer = serializer; } public async Task<(bool, TResult)> TryGetAsync(string key, CancellationToken cancellationToken, bool continueOnCapturedContext) { (bool, TSerialized) obj = await this._wrappedCacheProvider.TryGetAsync(key, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext); bool item = obj.Item1; TSerialized item2 = obj.Item2; return (item, item ? this._serializer.Deserialize(item2) : default(TResult)); } public async Task PutAsync(string key, TResult value, Ttl ttl, CancellationToken cancellationToken, bool continueOnCapturedContext) { await this._wrappedCacheProvider.PutAsync(key, this._serializer.Serialize(value), ttl, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext); } } }