.NET › Caching (In-Memory, Distributed & Redis)

How do you handle cache serialization for complex objects when using IDistributedCache, given it only natively supports byte[]?

Advanced

Answer

IDistributedCache's core API (GetAsync/SetAsync) works with raw byte[], so caching complex objects requires manual serialization (commonly System.Text.Json to UTF-8 bytes) before storing and deserialization after retrieval -- extension methods (GetStringAsync/SetStringAsync) simplify the string case, but for full object graphs you typically write a small helper or use a library wrapping this boilerplate consistently across your application.
public static class DistributedCacheExtensions {
    public static async Task SetObjectAsync<T>(this IDistributedCache cache, string key, T value, DistributedCacheEntryOptions options) {
        var bytes = JsonSerializer.SerializeToUtf8Bytes(value);
        await cache.SetAsync(key, bytes, options);
    }
    public static async Task<T?> GetObjectAsync<T>(this IDistributedCache cache, string key) {
        var bytes = await cache.GetAsync(key);
        return bytes == null ? default : JsonSerializer.Deserialize<T>(bytes);
    }
}
Real-world example A team writes a shared SetObjectAsync/GetObjectAsync extension method pair once, standardizing JSON serialization for distributed cache usage across dozens of services instead of each developer reimplementing serialization logic inconsistently.

Common follow-ups: What are the performance trade-offs of JSON versus binary serialization formats like MessagePack for caching?;How do you handle versioning when a cached object's schema changes?