SerializingCacheProvider<TSerialized>
Defines an ISyncCacheProvider which serializes objects of any type 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<TSerialized> : ISyncCacheProvider
{
private readonly ISyncCacheProvider<TSerialized> _wrappedCacheProvider;
private readonly ICacheItemSerializer<object, TSerialized> _serializer;
public SerializingCacheProvider(ISyncCacheProvider<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 object Get(string key)
{
TSerialized val = _wrappedCacheProvider.Get(key);
if (val != null && !val.Equals(default(TSerialized)))
return _serializer.Deserialize(val);
return null;
}
public void Put(string key, object value, Ttl ttl)
{
if (value != null)
_wrappedCacheProvider.Put(key, _serializer.Serialize(value), ttl);
}
}
}