A Generic Cache Manager in C# with MemoryCache

A cache keeps the result of an expensive operation, such as a database query, an HTTP call or a large calculation, so the next request can reuse it. The class below gives you a typed cache with optional expiration. Instead of managing a dictionary and timers by hand, it builds on MemoryCache from Microsoft.Extensions.Caching.Memory, which handles expiration, eviction under memory pressure and thread safety for you.

dotnet add package Microsoft.Extensions.Caching.Memory

ASP.NET Core apps already reference it.

Usage

using Microsoft.Extensions.Caching.Memory;

var memoryCache = new MemoryCache(new MemoryCacheOptions());
var cache = new CacheManager<string>(memoryCache);

cache.Add("key1", "data1", TimeSpan.FromSeconds(5)); // expires after 5 seconds
cache.Add("key2", "data2");                          // stays until removed or evicted

if (cache.TryGet("key1", out string? value))
{
    Console.WriteLine(value); // data1
}

cache.Remove("key2");

The most useful method is GetOrCreateAsync: return the cached value if there is one, otherwise run the factory, store the result and return it.

var products = new CacheManager<List<Product>>(memoryCache);

List<Product>? list = await products.GetOrCreateAsync(
    "all-products",
    () => repository.GetAllProductsAsync(),
    TimeSpan.FromMinutes(10));

The class

using Microsoft.Extensions.Caching.Memory;

public sealed class CacheManager<T>(IMemoryCache cache)
{
    public void Add(string key, T value, TimeSpan? lifetime = null)
    {
        var options = new MemoryCacheEntryOptions();
        if (lifetime is { } duration)
        {
            options.AbsoluteExpirationRelativeToNow = duration;
        }
        cache.Set(CacheKey(key), value, options);
    }

    public bool TryGet(string key, out T? value) =>
        cache.TryGetValue(CacheKey(key), out value);

    public Task<T?> GetOrCreateAsync(string key, Func<Task<T>> factory, TimeSpan lifetime) =>
        cache.GetOrCreateAsync(CacheKey(key), entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = lifetime;
            return factory();
        });

    public void Remove(string key) => cache.Remove(CacheKey(key));

    // Include T in the key so CacheManager<int> and CacheManager<string>
    // can share one IMemoryCache without overwriting each other's entries.
    private static (Type, string) CacheKey(string key) => (typeof(T), key);
}

IMemoryCache accepts any object as a key, and a value tuple has proper equality, so (typeof(T), key) works without string concatenation.

Why not a Dictionary and a Timer

The original version of this class stored items in a Dictionary<string, T> and started a System.Threading.Timer per item to remove it later. That has three problems that are easy to miss:

  • Not thread safe. Caches are shared by definition, and a Dictionary modified from several threads, including the timer callbacks, can corrupt itself and throw or loop forever. MemoryCache is safe for concurrent use.
  • Timers that never fire. The timer was a local variable. Once nothing references a Timer, the garbage collector can collect it, and its callback never runs, so items silently stay in the cache forever.
  • Unbounded growth. Nothing limited the number of entries.

MemoryCache does not use a timer per entry. It checks expiration when an entry is read, and at most once per ExpirationScanFrequency (one minute by default) it sweeps out expired entries during other cache operations. An expired item is therefore never returned, but it may occupy memory a little longer than its lifetime.

Absolute or sliding expiration

AbsoluteExpirationRelativeToNow removes an entry a fixed time after it was added, whether anyone used it or not. That is the right default for data that changes, because it bounds how stale the cache can get. SlidingExpiration instead extends the lifetime each time the entry is read, which suits things like per-user session data. If you use sliding expiration, combine it with an absolute limit, otherwise a popular entry may never be refreshed.

Limit the size

By default MemoryCache has no size limit. To cap it, set SizeLimit on the options and give every entry a Size in whatever unit you choose:

var memoryCache = new MemoryCache(new MemoryCacheOptions { SizeLimit = 1_000 });

memoryCache.Set("key", "value", new MemoryCacheEntryOptions { Size = 1 });

Once SizeLimit is set, every entry must have a size or Set throws InvalidOperationException. To use this with the class above, set options.Size in Add and entry.Size in GetOrCreateAsync.

In ASP.NET Core

Register the cache and the manager once, and let dependency injection share them:

builder.Services.AddMemoryCache();
builder.Services.AddSingleton(typeof(CacheManager<>));

Then inject CacheManager<Product> wherever you need it. The open generic registration means every T gets its own singleton, all backed by the same IMemoryCache. This replaces the singleton pattern the original post recommended.

One limitation to be aware of: GetOrCreateAsync does not lock. If ten requests miss the same key at once, the factory runs ten times. Usually that is acceptable. If the factory is expensive, look at HybridCache from the Microsoft.Extensions.Caching.Hybrid package, which lets only one caller run the factory per key and can add a distributed cache such as Redis behind the in-memory one.

Related examples

2 thoughts on “A Generic Cache Manager in C# with MemoryCache”

Leave a Comment