Skip to content

Implementing cache serializers

reisenberger edited this page Jan 6, 2018 · 6 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 to those. For example, for Redis you might have a:

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, you might implement (for example using Newtonsoft.Json):

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

Note: Redis and NewtonSoft.Json are referenced above to provide an easy-to-grok example of why you might need to implement a serializer. For these specific solutions, however, Polly already provides:

Using a serializer with the Polly CachePolicy

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

ISyncCacheProvider<TSerialized>.WithSerializer<TResult, TSerialized>(...) returns an ISyncCacheProvider<TResult>, the type needed in order to configure CachePolicy<TResult>. For example:

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

CachePolicy<TResult> cache = Policy.Cache<TResult>(
    redisCacheProvider.WithSerializer(jsonSerializer), 
    TimeSpan.FromMinutes(5) /* for example; see https://github.com/App-vNext/Polly/wiki/Cache#syntax for deeper options */
);

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. 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