Simple Memory Cache in ASP.NET Core

In this blog post, we'll explore how to use in-memory caching in ASP.NET Core. Caching can highly enhance the performance of your web application by reducing the number of times data needs to be retrieved or computed. We'll use a simple example to illustrate how you can implement in-memory caching in your ASP.NET Core application.

Setting Up the Project

First, let's set up our ASP.NET Core project. We'll start with the HomeController class, which will handle our web requests.

Here's the code for our HomeController:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly IMemoryCache _memoryCache;

    public HomeController(ILogger<HomeController> logger, IMemoryCache memoryCache)
    {
        _logger = logger;
        _memoryCache = memoryCache;
    }

    public IActionResult Index()
    {
        // Define a cache key 
        var cacheKey = "CachedDateTime";
        // Try to get the cached value 
        if (!_memoryCache.TryGetValue(cacheKey, out string cachedDateTime))
        {
            // If not cached, set the value 
            cachedDateTime = DateTime.Now.ToString("F");

            // Set cache options 
            var cacheEntryOptions = new MemoryCacheEntryOptions
            {
                // Set cache duration 
                AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10)
            };

            // Save the value in cache 
            _memoryCache.Set(cacheKey, cachedDateTime, cacheEntryOptions);
        }

        // Pass the cached value to the view 
        ViewData["CachedDateTime"] = cachedDateTime;
        return View();
    }
}

How It Works

1. Dependency Injection:
  • The HomeController constructor takes two parameters: ILogger<HomeController> and IMemoryCache.
  • ASP.NET Core's dependency injection (DI) system provides these services automatically.
2. Caching Logic:
  • Inside the Index action, we define a cache key, CachedDateTime.
  • We use _memoryCache.TryGetValue to check if the value associated with this key is already in the cache.
  • If the value is not in the cache, we set it to the current date and time (DateTime.Now.ToString("F")).
  • We define cache options using MemoryCacheEntryOptions to set an absolute expiration time of 10 seconds.
  • We store the value in the cache with _memoryCache.Set.
3. Passing Data to the View:
  • The cached value (current date and time) is passed to the view using ViewData.

Configuring Memory Cache

To enable memory caching, we need to add the memory cache service in the program.cs file:

builder.Services.AddMemoryCache();

This line registers the memory cache service with the ASP.NET Core dependency injection container.

Creating the View

Finally, let's create a simple view to display the cached date and time. Open the Index.cshtml file in the Views/Home directory and add the following code:
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Current Date and Time (cached for 10 seconds): @ViewData["CachedDateTime"]</p>
</div>

Running the Application

Run your application and navigate to the home page. You should see the current date and time displayed. Refresh the page within 10 seconds, and you'll see the same date and time due to the caching. After 10 seconds, the cached value expires, and you'll see the updated date and time on the next refresh.

Conclusion

In this blog post, we've seen how to implement in-memory caching in an ASP.NET Core application. This simple example demonstrates the power of caching to improve performance by reducing redundant data fetching or computation. With just a few lines of code, you can easily integrate caching into your applications and provide a better experience for your users.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

SignalR with JavaScript in ASP.NET Core MVC

Localization in ASP.NET Core MVC with Example