IC Improve Code Recipes

Recipe 3.6 · C#

A Typed Cache Wrapper

Problem

After a few years, cache keys are string literals scattered through the code, each call site picks its own lifetime, and the value type is whatever the caller casts it to. Nobody can answer the questions that matter: what is cached, for how long, and what invalidates it.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: keys, types and lifetimes decided at each call.
var profile = CacheManager.Get("Cust" + id) as CustomerProfile;
if (profile == null)
{
    profile = repo.LoadProfile(id);
    CacheManager.Add("Cust" + id, profile, 20);  // minutes? seconds?
}

// Elsewhere, years later:
CacheManager.Remove("Customer_" + id);  // a different key

The improved recipe

C#
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace ImproveCode.Caching;

public sealed record CacheKey<T>(string Name, TimeSpan TimeToLive)
{
    public override string ToString() => Name;
}

public sealed record CustomerProfile(
    int CustomerId, string DisplayName, string Tier);

public sealed record TaxRate(string Region, decimal Rate);

public static class CacheKeys
{
    public static CacheKey<CustomerProfile?> Customer(int id) =>
        new($"customer:v1:{id}", TimeSpan.FromMinutes(20));

    public static CacheKey<IReadOnlyList<TaxRate>> TaxRates { get; } =
        new("taxrates:v1", TimeSpan.FromHours(12));
}

public interface IAppCache
{
    Task<T> GetOrCreateAsync<T>(
        CacheKey<T> key,
        Func<CancellationToken, Task<T>> factory,
        CancellationToken ct = default);

    void Remove<T>(CacheKey<T> key);
}

public sealed class AppMemoryCache(SingleFlightCache cache) : IAppCache
{
    public Task<T> GetOrCreateAsync<T>(
        CacheKey<T> key,
        Func<CancellationToken, Task<T>> factory,
        CancellationToken ct = default) =>
        cache.GetOrCreateAsync(key.Name, factory, key.TimeToLive, ct);

    public void Remove<T>(CacheKey<T> key) => cache.Remove(key.Name);
}

// For unit tests: always calls the factory, caches nothing.
public sealed class NoCache : IAppCache
{
    public Task<T> GetOrCreateAsync<T>(
        CacheKey<T> key,
        Func<CancellationToken, Task<T>> factory,
        CancellationToken ct = default) => factory(ct);

    public void Remove<T>(CacheKey<T> key)
    {
    }
}

How it works

CacheKey<T> ties three facts together: the key string, the type stored under it, and how long it lives. Every key the application uses is defined once, in CacheKeys. The compiler now does the checking that used to happen at run time. GetOrCreateAsync(CacheKeys.Customer(id), ...) can only take a factory that returns a CustomerProfile?, and the result needs no cast.

Call sites become short and uniform:

C#
// Usage snippet
CustomerProfile? profile = await appCache.GetOrCreateAsync(
    CacheKeys.Customer(customerId),
    token => profiles.FindAsync(customerId, token),
    ct);

// After saving a profile change:
appCache.Remove(CacheKeys.Customer(customerId));

The reader and the writer both build the key through CacheKeys.Customer, so they cannot drift apart the way "Cust" and "Customer_" did. The v1 in each key gives you a versioning switch for when the cached type changes shape.

AppMemoryCache delegates to the SingleFlightCache from Recipe 3.4, so every typed entry gets stampede protection for free. Register both as singletons, with IAppCache mapped to AppMemoryCache. In unit tests, register NoCache instead and the code under test always reaches its repository, which keeps tests honest and independent of each other.

CacheKeys doubles as documentation. When someone asks what the application caches, the answer is one file, with every lifetime written next to its key.

Variations and pitfalls

  • A distributed implementation of IAppCache is a few lines over JsonDistributedCache from Recipe 3.5. Because callers depend on the interface, you can move from memory to Redis without touching them. Note that Remove would then need to be async; if you expect that move, define the interface with RemoveAsync from the start.
  • Keep CacheKeys small. If it grows past a few dozen entries, split it by feature (CustomerCacheKeys, PricingCacheKeys), but keep each key's lifetime next to its name.
  • Do not let the wrapper grow into a framework. Tags, regions and dependency graphs between entries are where homegrown cache managers go to become unmaintainable. Keep the wrapper this size and use HybridCache if you need more.
  • Normalize key parts. Build keys from invariant, normalized values: ToUpperInvariant() for codes, CultureInfo.InvariantCulture for numbers and dates. "customer:v1:42" must be the same string on every server.