SerializingCacheProvider<TResult, TSerialized>
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;
namespace Polly.Caching
{
public class SerializingCacheProvider<TResult, 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;
}
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, TResult value, Ttl ttl)
{
_wrappedCacheProvider.Put(key, _serializer.Serialize(value), ttl);
}
}
}