Implementing Memory Caching in ASP.NET Core Applications

ASP.NET Core provides built-in caching components that help improve application performance by storing frequently accesssed data in memory. The caching infrastructure supports multiple storage backends including in-memory cache, Redis, and SQL Server. This guide focuses on implementing in-memory caching in your ASP.NET Core applications.

Setting Up Memory Cache

To begin using memory caching, create a new ASP.NET Core web application project with authentication disabled for demonstration purposes.

Install the required NuGet package:

Install-Package Microsoft.Extensions.Caching.Memory

Register the memory cache service in the ConfigureServices method of your Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
    services.AddMvc();
}

Basic Cache Operations

Inject the IMemoryCache interface into your controller to perform cache operations:

public class ProductController : Controller
{
    private readonly IMemoryCache _cache;
    
    public ProductController(IMemoryCache cache)
    {
        _cache = cache;
    }

    public IActionResult GetProduct()
    {
        const string cacheKey = "product_list";
        string cachedData;
        
        if (!_cache.TryGetValue(cacheKey, out cachedData))
        {
            cachedData = $"ProductData_{DateTime.Now}";
            
            _cache.Set(cacheKey, cachedData);
        }
        
        ViewBag.Data = cachedData;
        return View();
    }
}

Advanced Cache Configuration

Memory cache supports various expiration policies and eviction options. The following examples demonstrate different caching strategies:

public IActionResult ConfigureCache()
{
    const string cacheKey = "user_session";
    string sessionData = $"UserSession_{DateTime.Now}";
    
    // Sliding expiration: cache expires after 2 minutes of inactivity
    _cache.Set(cacheKey, sessionData, new MemoryCacheEntryOptions()
        .SetSlidingExpiration(TimeSpan.FromMinutes(2)));
    
    // Absolute expiration: cache expires at a fixed time
    _cache.Set(cacheKey, sessionData, new MemoryCacheEntryOptions()
        .SetAbsoluteExpiration(TimeSpan.FromMinutes(2)));
    
    // Manual cache removal
    _cache.Remove(cacheKey);
    
    // Priority setting: determines eviction order under memory pressure
    _cache.Set(cacheKey, sessionData, new MemoryCacheEntryOptions()
        .SetPriority(CacheItemPriority.NeverRemove));
    
    // Eviction callback: triggered when cache entry is removed
    _cache.Set(cacheKey, sessionData, new MemoryCacheEntryOptions()
        .SetAbsoluteExpiration(TimeSpan.FromSeconds(10))
        .RegisterPostEvictionCallback((key, value, reason, substate) =>
        {
            Console.WriteLine($"Key: {key}, Value: {value}, Reason: {reason}");
        }));
    
    // Token-based expiration
    var cancellationTokenSource = new CancellationTokenSource();
    _cache.Set(cacheKey, sessionData, new MemoryCacheEntryOptions()
        .AddExpirationToken(new CancellationChangeToken(cancellationTokenSource.Token))
        .RegisterPostEvictionCallback((key, value, reason, substate) =>
        {
            Console.WriteLine($"Key: {key}, Value: {value}, Reason: {reason}");
        }));
    
    cancellationTokenSource.Cancel();
    
    ViewBag.Data = sessionData;
    return View();
}

Using Distributed Cache Tag Helper

ASP.NET Core MVC providees a convenient tag helper for caching view content. Simply add the distributed-cache element to your Razor views:

<distributed-cache name="userprofile" expires-after="TimeSpan.FromSeconds(15)">
    <p>This content is cached for 15 seconds</p>
    @DateTime.Now
</distributed-cache>

<distributed-cache name="dashboard" expires-sliding="TimeSpan.FromSeconds(30)">
    <p>Content remains cached while accessed within 30 seconds</p>
    @DateTime.Now
</distributed-cache>

The first example uses absolute expiration, while the second implements sliding expiration that resets the timer on each access.

Tags: aspnet-core Caching memory-cache dotnet distributed-cache

Posted on Fri, 08 May 2026 10:59:25 +0000 by surfer