How to implement simple Memory Cache for Web API

By FoxLearn 5/31/2024 9:17:56 AM   91
This post shows you How to implement memory cache for ASP.NET Web API in C#

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.

Implementing a memory cache for an ASP.NET Web API in C# can significantly improve performance by storing frequently accessed data in memory. 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 MemoryCache class available in the System.Runtime.Caching namespace for this purpose. Here's a basic guide on how to implement it:

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 System.Runtime.Caching in your project.

Create a utility class for caching data. This class will handle all interactions with the cache.

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 don't 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));

You can adjust the expiration time and other caching policies as per your requirements.

Related