20 min read

Implementing In-Memory Caching in ASP.NET Core Web API


In modern web applications, performance optimization is crucial for user satisfaction and operational efficiency. One effective method to enhance application performance is caching. In-memory caching, in particular, can dramatically speed up applications by storing frequently accessed data in memory. This article will explore how to implement in-memory caching in ASP.NET Core Web API a .NET 8 application using the IMemoryCache interface.

Introduction to In-Memory Caching

In-memory caching stores data in the server’s memory, avoiding the need to repeatedly fetch data from slower sources like databases or external APIs. This can significantly reduce response times and decrease load on your databases.

.NET 8 provides built-in support for in-memory caching through the IMemoryCache interface, which is part of the Microsoft.Extensions.Caching.Memory namespace. It offers a simple yet powerful API to cache and retrieve data.

Setting Up In-Memory Caching

To begin using in-memory caching, you need to configure your application to use the IMemoryCache service. This setup typically occurs in your Program.cs file.

Step 1: Add Memory Cache Service

First, add the memory cache service to your service collection to make it available throughout your application:

using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddMemoryCache();

var app = builder.Build();

// Continue configuring the app

Utilizing IMemoryCache in Your Application

With the service configured, you can inject IMemoryCache into controllers, services, or wherever you need caching functionality.

Step 2: Inject and Use IMemoryCache

Here is an example of how to use IMemoryCache in a controller to cache data:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

public class MyController : ControllerBase
{
    private readonly IMemoryCache _cache;

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

    [HttpGet("get/data")]
    public IActionResult GetData()
    {
        var cacheKey = "my-data";
        if (!_cache.TryGetValue(cacheKey, out string data))
        {
            // Fetch the data if not in the cache
            data = "This is the data to cache.";

            // Define cache options
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromMinutes(2))
                .SetAbsoluteExpiration(TimeSpan.FromHours(1));

            // Set the data in the cache
            _cache.Set(cacheKey, data, cacheEntryOptions);
        }

        return Ok(data);
    }
}

Key Features of ‘IMemoryCache’

  • Cache Eviction: Control when an item is removed from the cache using expiration settings:
    • SetAbsoluteExpiration defines a fixed duration after which the cache entry expires.
    • SetSlidingExpiration resets the expiration time whenever the cache entry is accessed, keeping frequently used data in cache longer.
  • Cache Priority: Assign priorities to cache entries to influence their retention during memory pressure.

Conclusion

Implementing in-memory caching in your ASP.NET Core Web API .NET 8 applications can significantly enhance performance by reducing data retrieval times and lowering backend load. By following the steps outlined above, you can effectively integrate the IMemoryCache interface into your .NET applications, ensuring faster and more responsive service delivery.

Support ❤️
If you have enjoyed my content and code, do support me by buying a couple of coffees. This will enable me to dedicate more time to research and create new content. Cheers!
Share this Article
Share this article with your network to help others!
What's your Feedback?
Do let me know your thoughts around this article.