SerializingCacheProviderAsync<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 SerializingCacheProviderAsync<TSerialized> : IAsyncCacheProvider
{
private readonly IAsyncCacheProvider<TSerialized> _wrappedCacheProvider;
private readonly ICacheItemSerializer<object, TSerialized> _serializer;
public SerializingCacheProviderAsync(IAsyncCacheProvider<TSerialized> wrappedCacheProvider, ICacheItemSerializer<object, TSerialized> serializer)
{
if (wrappedCacheProvider == null)
throw new ArgumentNullException("wrappedCacheProvider");
if (serializer == null)
throw new ArgumentNullException("serializer");
_wrappedCacheProvider = wrappedCacheProvider;
_serializer = serializer;
}
public async Task<object> GetAsync(string key, CancellationToken cancellationToken, bool continueOnCapturedContext)
{
TSerialized objectToDeserialize = await this._wrappedCacheProvider.GetAsync(key, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext);
return this._serializer.Deserialize(objectToDeserialize);
}
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);
}
}
}