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

AsyncSerializingCacheProvider<TSerialized>

Defines an IAsyncCacheProvider which serializes objects of any type 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<TSerialized> : IAsyncCacheProvider { private readonly IAsyncCacheProvider<TSerialized> _wrappedCacheProvider; private readonly ICacheItemSerializer<object, TSerialized> _serializer; public AsyncSerializingCacheProvider(IAsyncCacheProvider<TSerialized> wrappedCacheProvider, ICacheItemSerializer<object, TSerialized> serializer) { if (wrappedCacheProvider == null) throw new ArgumentNullException("wrappedCacheProvider"); _wrappedCacheProvider = wrappedCacheProvider; if (serializer == null) throw new ArgumentNullException("serializer"); _serializer = serializer; } public async Task<(bool, object)> 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) : null); } public async Task PutAsync(string key, object value, Ttl ttl, CancellationToken cancellationToken, bool continueOnCapturedContext) { await this._wrappedCacheProvider.PutAsync(key, this._serializer.Serialize(value), ttl, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext); } } }