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

Introduction

Caching is a crucial technique for improving the performance and responsiveness of web applications by storing frequently accessed data in memory. In the ASP.NET Core Web API, you can easily implement an in-memory cache using the IMemoryCache interface provided by the framework. In this article, we'll walk through a complete practical example of implementing and using an in-memory cache in an ASP.NET Core Web API project.

Step 1. Create a New ASP.NET Core Web API Project

First, let's create a new ASP.NET Core Web API project using Visual Studio or the.NET CLI. Open your preferred development environment and run the following command to create a new Web API project:

dotnet new webapi -n InMemoryCacheExample

This command will create a new ASP.NET Core Web API project named InMemoryCacheExample.

Step 2. Add Memory Cache Service

Open the Startup.cs file in your project and add the memory cache service to the services collection in the ConfigureServices method:

Step 3. Create a Sample Data Model and Controller

Let's create a simple data model and a controller to demonstrate caching. Create a new folder named Models in your project and add a class named Product.cs with the following code:

namespace _101InMemoryCacheInAspNetCore.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }

}

Next, create a new controller named ProductsController.cs in the Controllers folder with the following code:

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

namespace _101InMemoryCacheInAspNetCore.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private readonly IMemoryCache _memoryCache;

        public ProductsController(IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
        }

        [HttpGet("{id}")]
        public ActionResult<Product> Get(int id)
        {
            if (_memoryCache.TryGetValue($"Product_{id}", out Product cachedProduct))
            {
                return Ok(cachedProduct);
            }
            else
            {
                var product = new Product { Id = id, Name = $"Product {id}", Price = 99.99M };

                _memoryCache.Set($"Product_{id}", product, TimeSpan.FromMinutes(10));

                return Ok(product);
            }
        }
    }
}

In this controller, we inject the IMemoryCache interface into the constructor. The Get method first checks if the product with the specified ID exists in the cache. If found, it returns the cached product. Otherwise, it simulates fetching the product from a data source, stores it in the cache for 10 minutes, and then returns it.

Step 4. Test the Web API

Build and run your ASP.NET Core Web API project. You can use tools like Postman or curl to test the API endpoints.

Send a GET request to https://localhost:{port}/products/{id} (replace {port} with your actual port number and {id} with a product ID).
For the first request with a specific product ID, the data will be fetched and stored in the cache.
Subsequent requests with the same product ID will retrieve the data from the cache instead of fetching it again.

Step 5. Additional Cache Operations

You can perform additional cache operations such as setting cache expiration, removing items from the cache, or using cache dependencies based on your application's requirements. Here are a few examples:

// Set cache expiration with sliding expiration
_memoryCache.Set("Key", value, new MemoryCacheEntryOptions
{
    SlidingExpiration = TimeSpan.FromMinutes(5)
});

// Remove item from cache
_memoryCache.Remove("Key");

// Use absolute expiration
_memoryCache.Set("Key", value, DateTimeOffset.Now.AddMinutes(10));

Importance of an In-Memory Cache

The importance of using IMemory Cache lies in its ability to significantly enhance the performance and scalability of ASP.NET Core Web API applications. Here are some key reasons why IMemory Cache is important:

  1. Improved Performance: By storing frequently accessed data in memory, IMemory Cache reduces the need to fetch data from slower data sources such as databases or external APIs. This leads to faster response times and better overall performance of your web API.

  2. Reduced Latency: Caching data in memory reduces the latency associated with fetching data from external sources. This is especially beneficial for data that doesn't change frequently and can be safely cached for a certain period.

  3. Scalability: Caching helps in optimizing resource usage and improving the scalability of your application. By reducing the workload on backend systems, you can handle more concurrent requests without compromising performance.

  4. Cost Savings: Caching data in memory can result in cost savings by reducing the number of calls made to external services or databases. This can be particularly important when dealing with cloud-based services where each API call incurs costs.

  5. Customizable Caching Strategies: IMemory Cache provides flexibility in defining caching strategies such as expiration times, cache dependencies, and eviction policies. This allows developers to tailor caching behavior based on the specific requirements of their application.

  6. Enhanced User Experience: Faster response times and reduced latency contribute to an improved user experience, leading to higher user satisfaction and retention rates.

IMemory Cache is a valuable tool for optimizing the performance, scalability, and cost-effectiveness of ASP.NET Core Web API applications, ultimately resulting in a better overall experience for both users and developers.

Output

Memory Cache

GitHubProject Link

https://github.com/SardarMudassarAliKhan/101InMemoryCacheInAspNetCore

Conclusion

Implementing an in-memory cache in an ASP.NET Core Web API can significantly improve the performance of your application by reducing the load on data sources and speeding up data retrieval for frequently accessed resources. By following the steps outlined in this article and customizing caching options as needed, you can effectively leverage caching in your ASP.NET Core Web API projects.