How to implement simple Memory Cache for Web API

This post shows you How to implement memory cache for ASP.NET Web API using C# Code.

Caching helps reduce access to frequently accessed data and less changes in the database, so the application will run faster. Remember that you must ensure that two criteria are regular access level and little change in data.

For example: Product catalog, user rights, product view...etc. This increases the speed of loading pages because data is cached available on memory and saves time.

Sometimes you will need to cache some temporary things on memory to increase the performance of the program in ASP.NET Web API. There are a few helpful libraries to help you do that, popular is CacheCow library. But if you want to use caching and don't want to use a 3rd party library you can use the System.Runtime.Caching.dll.

Caching for Web API doesn't use third parties

You only need to use an integration class called MemoryCache located in the System.Runtime.Caching.dll library. Before using the MemoryCache class you need to Add Reference to the library: System.Runtime.Caching

Create a utility class for caching data:

public class MemoryCacheHelper
{
    /// <summary>
    /// Get cache value by key
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static object GetValue(string key)
    {
        return MemoryCache.Default.Get(key);
    }

    /// <summary>
    /// Add a cache object with date expiration
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <param name="absExpiration"></param>
    /// <returns></returns>
    public static bool Add(string key, object value, DateTimeOffset absExpiration)
    {
        return MemoryCache.Default.Add(key, value, absExpiration);
    }

    /// <summary>
    /// Delete cache value from key
    /// </summary>
    /// <param name="key"></param>
    public static void Delete(string key)
    {
        MemoryCache memoryCache = MemoryCache.Default;
        if (memoryCache.Contains(key))
            memoryCache.Remove(key);
    }
}

And when you want to caching something, just add it to the cache with a unique key and the value of the cache:

And when using, just get out under that key:

var products = MemoryCacheHelper.GetValue("products");

Note: You should remember that MemoryCache will be deleted every time the IIS app pool is refreshed.

If your Web API:

  • Do not receive any request for more than 20 minutes
  • Or set the default time for IIS to refresh the Pool to 1740 minutes
  • Or you deploy a new build on the Web API directory on IIS

You should have a manual operation. If you can't get the value from the cache, you should get it from the database and then reassign it to the cache:

var list = MemoryCacheHelper.GetValue("products");
if (list == null)
     MemoryCacheHelper.Add("products", new List<string>() { "A", "B", "C" }, DateTimeOffset.UtcNow.AddHours(2));