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

SerializingCacheProviderAsync<TResult, TSerialized>

public class SerializingCacheProviderAsync<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 SerializingCacheProviderAsync<TResult, TSerialized> : IAsyncCacheProvider<TResult> { private readonly IAsyncCacheProvider<TSerialized> _wrappedCacheProvider; private readonly ICacheItemSerializer<TResult, TSerialized> _serializer; public SerializingCacheProviderAsync(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<TResult> GetAsync(string key, CancellationToken cancellationToken, bool continueOnCapturedContext) { TSerialized val = await this._wrappedCacheProvider.GetAsync(key, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext); return (val == null || val.Equals(default(TSerialized))) ? default(TResult) : this._serializer.Deserialize(val); } public async Task PutAsync(string key, TResult value, Ttl ttl, CancellationToken cancellationToken, bool continueOnCapturedContext) { if (value != null && !value.Equals(default(TResult))) await this._wrappedCacheProvider.PutAsync(key, this._serializer.Serialize(value), ttl, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext); } } }