In-Memory Cache in ASP.NET

What is In-Memory Cache?

In-Memory Cache is a feature in ASP.NET that allows you to temporarily store data in the server's memory. This reduces the need for repetitive database or API calls, improving performance.

  • Fast Access: Data is stored in memory for quick retrieval.
  • Improves Performance: Reduces database load and response time.
  • Easy to Implement: Built-in support in ASP.NET Core.

How to Implement In-Memory Cache

Follow these steps to use in-memory caching in your application:

1. Register the In-Memory Cache Service


// Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMemoryCache(); // Register in-memory cache
builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();

app.Run();

                

The AddMemoryCache method enables in-memory caching in the application.

2. Inject IMemoryCache in a Controller


// Controllers/WeatherController.cs
[ApiController]
[Route("api/weather")]
public class WeatherController : ControllerBase
{
    private readonly IMemoryCache _cache;

    public WeatherController(IMemoryCache cache)
    {
        _cache = cache;
    }

    [HttpGet]
    public IActionResult GetWeather()
    {
        const string cacheKey = "weatherData";
        if (!_cache.TryGetValue(cacheKey, out string weather))
        {
            // Simulate fetching data (e.g., from an API)
            weather = "Sunny, 25°C";

            // Set cache options
            var cacheOptions = new MemoryCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10),
                SlidingExpiration = TimeSpan.FromMinutes(2)
            };

            // Store data in cache
            _cache.Set(cacheKey, weather, cacheOptions);
        }
        return Ok(weather);
    }
}

                

The TryGetValue method checks if the data is already in the cache. If not, it stores the fetched data with specific expiration options.

3. Configure Cache Expiration


// Example of Cache Options
var cacheOptions = new MemoryCacheEntryOptions
{
    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5), // Data expires in 5 minutes
    SlidingExpiration = TimeSpan.FromMinutes(1) // Resets expiration if accessed within 1 minute
};
_cache.Set("key", "value", cacheOptions);

                

Absolute Expiration: Ensures the data expires after a set duration.
Sliding Expiration: Extends the expiration time if the cache is accessed.

4. Remove Data from Cache


// Remove data from cache
_cache.Remove("weatherData");

                

Use the Remove method to delete data from the cache when it is no longer valid.

5. Example Request and Response


// GET /api/weather
Response: "Sunny, 25°C"

// After Cache Expiration
GET /api/weather
Response: "Sunny, 25°C" (Data reloaded and cached again)

                

Test the caching behavior using tools like Postman or your browser.