Skip to content

Implementing cache serializers

reisenberger edited this page Dec 9, 2017 · 5 revisions

Cache: Implementing serializers

The Polly.Caching namespace provides an ICacheItemSerializer<TResult, TSerialized> interface.

Implementations of this interface allow you to serialize items for placing in the cache, and deserialize again on retrieving from cache.

Creating serializers

The interface ICacheItemSerializer<TResult, TSerialized> is very simple to fulfil:

public interface ICacheItemSerializer<TResult, TSerialized>
{
    TSerialized Serialize(TResult objectToSerialize);
    TResult Deserialize(TSerialized objectToDeserialize);
}

Why do we need serializers?

Some cache providers (such as Redis) store most items as specific types (eg string or byte[]), requiring you to serialize more complex types. For example, for Redis you might implement:

RedisCacheProvider<string>: ISyncCacheProvider<string>, IAsyncCacheProvider<string>

The above RedisCacheProvider<string> (as is) would only be usable in CachePolicy<string>. To use the cache for other result types, implement (for example using Newtonsoft.Json):

JsonSerializer<TResult, string> : ICacheItemSerializer<TResult, string>
{
    string Serialize(TResult objectToSerialize);
    TResult Deserialize(string objectToDeserialize);
}

Using the serializer with the Polly CachePolicy

An in-built extension method in Polly, .WithSerializer<TResult, TSerialized>(), then allows you to bridge from the native TResult of the execution to the serialized TSerialized type.

ISyncCacheProvider<TSerialized>.WithSerializer<TResult, TSerialized>() returns an ISyncCacheProvider<TResult> (which is expected by the configuration syntax for CachePolicy<TResult>), allowing you to bridge as follows:

ISyncCacheProvider<string> redisCacheProvider = ... // configured earlier
ICacheItemSerializer<TResult, string> jsonSerializer = ... // configured earlier

CachePolicy<TResult> cache = Policy.Cache<TResult>(
    redisCacheProvider.WithSerializer<TResult, string>(jsonSerializer), 
    TimeSpan.FromMinutes(5));

The above examples are based around serializing to string using Newtonsoft.Json as this is one of the most commonly understood serialization approaches. However, it is far from the only option. Redis, for example, can also store any kind of byte[] array as a Redis 'string'. For a fuller overview of serialization options available, see the Microsoft Patterns-and-Practices article on Caching, section Serialization considerations.

Community contributions

Community contributions of new third-party serializers for Polly will be very welcome. Let us know, and we can make new providers available to the wider Polly community (with full credit to the original contributors).

Clone this wiki locally