Harnessing the Power of Caching in ASP.NET
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
- Mastering Git Repository Organization
- CancellationToken for Async Programming
- Git Flow Rethink: When Process Stops Paying Rent
- Understanding System Cache: A Comprehensive Guide
- Guide to Redis Local Instance Setup
- Fire and Forget for Enhanced Performance
- Building Resilient .NET Applications with Polly
- The Singleton Advantage: Managing Configurations in .NET
- Troubleshooting and Rebuilding My JS-Dev-Env Project
- Decorator Design Pattern - Adding Telemetry to HttpClient
- Generate Wiki Documentation from Your Code Repository
- TaskListProcessor - Enterprise Async Orchestration for .NET
- Architecting Agentic Services in .NET 9: Semantic Kernel
- NuGet Packages: Benefits and Challenges
- My Journey as a NuGet Gallery Developer and Educator
- Harnessing the Power of Caching in ASP.NET
- The Building of React-native-web-start
- TailwindSpark: Ignite Your Web Development
- Creating a PHP Website with ChatGPT
- Evolving PHP Development
- Modernizing Client Libraries in a .NET 4.8 Framework Application
- Building Git Spark: My First npm Package Journey
- 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.CachingBasic 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
- Decorator Design Pattern - Adding Telemetry to HttpClient -- Adding Telemetry to HttpClient in ASP.NET Core
- My Journey as a NuGet Gallery Developer and Educator -- From Creation to Education in the NuGet Ecosystem
- NuGet Packages: Benefits and Challenges -- Exploring the Pros and Cons of NuGet Packages
- Mastering Git Repository Organization -- Enhance Collaboration and Project Management with Git
- Guide to Redis Local Instance Setup -- Master the Setup of Redis on Your Local Machine


