Using Cache in ASP.NET CORE

Caching is used to improve performance of application the data which does not change frequently can be added to the cache.

E.g. Think if you have a static data in SQL table you have 50000 users on your portal it will hit all 50000 times for getting it and every refresh will hit more this will use some of you SQL server resource without any need.

The cache will make you save some resource of SQL server or any other database you use.
To use Cache, we need to Register IMemoryCache (AddMemoryCache) Service in ConfigureServices startup class.

Service to Add in Startup Class

services.AddMemoryCache();
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace WebApplication2
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

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

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Now we have registered IMemoryCache service let’s learn how to store and retrieve the value from it.

MemoryCacheEntryOptions
AbsoluteExpiration:- will expire the entry after a set amount of time.
SlidingExpiration: – will expire the entry if it hasn’t been accessed in a set amount of time.

Setting Cache

For showing demo, I have added a New Controller with name Demo5 and Create ActionMethod in it.
First simple demo first we are going to store a string in cache later will show you how to store collection in ASP.NET Core MVC.

We have registered MemoryCache service in ConfigureServices method in startup class, for accessing it we are going to use Constructor injection as you can see code, we have injected IMemoryCache service.

Now we have added Create action method in that we are going to set value to cache for setting value we need key for demo I have added key “FirstKey“, along with that we also have to set Expiration for cache to expire for that we need to use MemoryCacheEntryOptions were we have option to set AbsoluteExpiration, SlidingExpiration, for demo we are using SlidingExpiration with timing 5 minutes of timespan next we are going set cache for doing that we need to pass key, value to store and MemoryCacheEntryOptions.   

private readonly IMemoryCache _iMemoryCache;

 public Demo5Controller(IMemoryCache memoryCache)
 {
     _iMemoryCache = memoryCache;
 }

 public IActionResult Create()
 {
     string key = "FirstKey";
     // Set cache options.
     var cacheEntryOptions = new MemoryCacheEntryOptions().
         SetSlidingExpiration(TimeSpan.FromMinutes(5));

     _iMemoryCache.Set(key, "Hello MemoryCache", cacheEntryOptions);

     return View();
 }

Next, let’s read value which is stored in that MemoryCache with a key.

Reading Stored Cache

For reading values from Memory cache we are going to use Get Method with the key.

public IActionResult Read()
{
    string key = "FirstKey";
    var value = _iMemoryCache.Get<string>(key);
    return View();
}

Removing Stored Cache

For removing value from the cache stored we need to use Remove method with the key.

public IActionResult Remove()
{
     string key = "FirstKey";
     _iMemoryCache.Remove(key);
     return View();
}

Check Key already exists or Create

In MemoryCache we also have a method where we can get value if already exits else it will create.

public IActionResult GetOrCreateCache()
{
     string key = "FirstKey";

     var cacheEntry = _iMemoryCache.GetOrCreate(key, entry =>
     {
         entry.SlidingExpiration = TimeSpan.FromMinutes(5);
         return "Hello MemoryCache 2";
     });

     return View();
 }

Check Key already exists or Create in Async way

This method functions similar to GetOrCreate method but it does in an asynchronous way.

public async Task<IActionResult> GetOrCreateAsyncCache()
 {
     string key = "FirstKey";
     var cacheEntry = await
         _iMemoryCache.GetOrCreateAsync(key, entry =>
         {
             entry.SlidingExpiration = TimeSpan.FromMinutes(5);
             return Task.FromResult("Hello MemoryCache 3");
         });

     return View("Index");
 }

By Saineshwar Bageri

I am Microsoft MVP | C# Corner MVP | Code Project MVP | FULL STACK .NET Developer and working on .Net Web Technology (Asp.net, Asp.net Core,.Net Core, C#, Sqlserver, MVC, Windows, Console Application, javascript, jquery, json, ORM Dapper) and also a freelance developer.