Back to blog

Harnessing the Power of Caching in ASP.NET

July 20, 20253 min read

Caching is essential for optimizing ASP.NET applications. This article explores how to use MemoryCacheManager to implement effective caching strategies, improving performance and scalability.

Development Series — 23 articles
  1. Mastering Git Repository Organization
  2. CancellationToken for Async Programming
  3. Git Flow Rethink: When Process Stops Paying Rent
  4. Understanding System Cache: A Comprehensive Guide
  5. Guide to Redis Local Instance Setup
  6. Fire and Forget for Enhanced Performance
  7. Building Resilient .NET Applications with Polly
  8. The Singleton Advantage: Managing Configurations in .NET
  9. Troubleshooting and Rebuilding My JS-Dev-Env Project
  10. Decorator Design Pattern - Adding Telemetry to HttpClient
  11. Generate Wiki Documentation from Your Code Repository
  12. TaskListProcessor - Enterprise Async Orchestration for .NET
  13. Architecting Agentic Services in .NET 9: Semantic Kernel
  14. NuGet Packages: Benefits and Challenges
  15. My Journey as a NuGet Gallery Developer and Educator
  16. Harnessing the Power of Caching in ASP.NET
  17. The Building of React-native-web-start
  18. TailwindSpark: Ignite Your Web Development
  19. Creating a PHP Website with ChatGPT
  20. Evolving PHP Development
  21. Modernizing Client Libraries in a .NET 4.8 Framework Application
  22. Building Git Spark: My First npm Package Journey
  23. Dave's Top Ten: Git Stats You Should Never Track

Harnessing the Power of Caching in ASP.NET

Understanding Caching in ASP.NET

On a recent project, I spent a week tuning cache expiration times because our report queries were either serving stale data or hammering the database. The same query was firing 50 times per minute from the same user session—a five-minute cache window cut that load by 80%. But deciding what to cache, how long to hold it, and what to do when it goes wrong turned out to be harder than writing the code itself. That's what led me to MemoryCacheManager as a consistent pattern across ASP.NET projects.

In ASP.NET, in-memory caching stores data temporarily so you're not repeatedly fetching it from a database or external service. The MemoryCache class from System.Runtime.Caching is the underlying mechanism. What I've found useful is wrapping it in a thin manager class that enforces consistent expiration policies and keeps cache access out of my business logic.

Introduction to MemoryCacheManager

MemoryCacheManager sits on top of the MemoryCache class from the System.Runtime.Caching namespace. I typically reach for this pattern because it centralizes cache policy decisions—expiration, dependency management, eviction—in one place rather than scattering MemoryCache.Default calls across the codebase.

Key Features of MemoryCacheManager

The API is straightforward—I can add, retrieve, and remove items in a few lines. It supports both absolute and sliding expiration, which I've used to handle different refresh patterns: absolute expiration for report data that should refresh on a schedule, sliding expiration for user session data that should stay warm while it's being used. Cache dependencies let you tie an entry's validity to another resource, which helps keep data consistent without manual invalidation.

Implementing MemoryCacheManager

Setting Up Your Project

To get started with MemoryCacheManager, reference the System.Runtime.Caching library. Add it via NuGet:

Install-Package System.Runtime.Caching

Basic Usage Example

Here's a simple example of how to use MemoryCacheManager in an ASP.NET application:

using System;
using System.Runtime.Caching;

public class MemoryCacheManager
{
    private static readonly ObjectCache Cache = MemoryCache.Default;

    public void AddItem(string key, object value, int expirationMinutes)
    {
        var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(expirationMinutes) };
        Cache.Add(key, value, policy);
    }

    public object GetItem(string key)
    {
        return Cache[key];
    }

    public void RemoveItem(string key)
    {
        Cache.Remove(key);
    }
}

Advanced Caching Strategies

  • Sliding expiration keeps items in cache as long as they are accessed within a specified time.
  • Cache dependencies automatically invalidate cache entries when a dependent item changes.

When MemoryCacheManager Works Well—and When It Doesn't

In my experience, MemoryCacheManager earns its keep when data is expensive to compute but doesn't change often: report aggregations, reference lookups, configuration values. The performance gains are real and the code stays simple.

What I've learned the hard way is where it breaks down. First, GetItem returns null when a key isn't found—or when the entry has expired. I've watched developers call GetItem and dereference the result without a null check, which produces intermittent null reference exceptions that are genuinely annoying to trace. Always check the return value.

Second, in-memory cache doesn't survive a process recycle. On any load-balanced or containerized deployment, each instance maintains its own cache, so two users hitting different nodes can see different data. That's the point where I stop using MemoryCacheManager and reach for a distributed cache like Redis instead.

Third, sliding expiration can quietly mask stale data. If a cached item stays continuously warm because it's popular, it may never expire—even if the underlying data has changed. The trade-off here is between cache efficiency and data freshness, and it's worth being deliberate about which expiration policy you choose for each data type.

Conclusion

MemoryCacheManager shines for data that's expensive to compute but doesn't change often. I've found it less helpful in distributed systems where cache invalidation becomes the hard part—there, a distributed cache is the better tool. For single-server or single-process ASP.NET applications, though, this pattern consistently reduces database load and keeps response times predictable without adding much operational complexity.

Explore More