Asp.Net Core Memory Cache Management

How to Manage Memory Cache in Asp.Net Core?


Memory Cache has an important place in Asp.Net applications. In general, it is used to access the data without always going to the database by recording the type of data we want in memory. We will show you cache management using the IMemoryCache feature available on Asp.Net Core.

Before we start, we would like to share with you the CacheManager class we use.

 

public class CacheManager
    {
        private static CancellationTokenSource _resetCacheToken = new CancellationTokenSource();
        private readonly IMemoryCache _memoryCache;
        /// <summary>
        /// Cache Manager
        /// </summary>
        /// <param name="memoryCache"></param>
        public CacheManager(IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
        }
        /// <summary>
        /// sets the cache entry T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expirationInMinutes"></param>
        /// <returns></returns>
        public T Set<T>(object key, T value, int expirationInMinutes = 60)
        {
            MemoryCacheEntryOptions options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal).SetAbsoluteExpiration(TimeSpan.FromMinutes(expirationInMinutes));
            options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));
            _memoryCache.Set(key, value, options);
            return value;
        }
        /// <summary>
        /// checks for cache entry existence
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Contains(object key)
        {
            return _memoryCache.TryGetValue(key, out object result);
        }
        /// <summary>
        /// returns cache entry T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(object key)
        {
            return _memoryCache.TryGetValue(key, out T result) ? result : default(T);
        }
        /// <summary>
        /// clear cache entry
        /// </summary>
        /// <param name="key"></param>
        public void Clear(object key)
        {
            _memoryCache.Remove(key);
        }
        /// <summary>
        /// expires cache entries T based on CancellationTokenSource cancel 
        /// </summary>
        public void Reset()
        {
            if (_resetCacheToken != null && !_resetCacheToken.IsCancellationRequested &&
                _resetCacheToken.Token.CanBeCanceled)
            {
                _resetCacheToken.Cancel();
                _resetCacheToken.Dispose();
            }
            _resetCacheToken = new CancellationTokenSource();
        }   
}

 

Before adding the CacheManager class to the place where we use it, add "services.AddMemoryCache();" to ConfigureServices in Startup.cs in the Asp.Net Core project. We need to add the Memory Cache service as follows. So if we look at the code block, it will look like this.

 

public IServiceProvider ConfigureServices(IServiceCollection services)
{
            services.AddMemoryCache();

 } 

 

Then we will need to add the CacheManager class to where we will use it. We want to add it to a different class we use. Now let's see how we added it to the class.

 

 public class MemoryHelper
{

  private readonly IMemoryCache memoryCache;
  private readonly CacheManager cacheManager; 

 public MemoryHelper( IMemoryCache _memoryCache)
 {
    memoryCache = _memoryCache;
    cacheManager = new CacheManager(memoryCache);
 }
}
 

 

As shown above, we add the CacheManager class into the different class we want to use. Now we can start cache management. We have a class of type Expense and we want to store the list of this class type in the cache. You can store your own class or dynamic object instead of the Expense class. Now let's look at how the storage process is done.

 

public List<Expense> GetExpenseList()
{
List<Expense> Expenses = new List<Expense>();
List<Expense> cachedData = cacheManager.Get<List<Expense>>("ExpenseList");
if (cachedData != null && cachedData.Any())
{
Expenses = cachedData;
}
else
{
for (int i = 0; i < 10; i++) // Here you need to pull data from the database and add it to the list. Or you need to fill out your list as you wish. We do it this way as an example.
{
Expenses.Add(new Expense());
}
// After filling out our list, we register with Cache Manager.
cacheManager.Set<List<Expense>>("ExpenseList", Expenses);

}
return Expenses;

}

 

 

The GetExpenseList method we wrote above first checks whether there is a cache registered with CacheManager. If there is data in the cache, it transfers it to the list. If the data we want is not available in the cache, it stores it in the cache for later use. The default time on Cache Manager is set to 60 minutes. If you want to store data for a longer period of time, "cacheManager.Set<List<Expense>>("ExpenseList", Expenses, 120);" You can also write as .

Using these operations, which will be useful for everyone, will increase the performance of your system, but you need to be very careful to avoid problems on your server due to too much data in the memory. Our advice to you is to perform these operations by taking your memory management into consideration.

We wish everyone good work.

 

Would you like to have an interview?

We help you with your business's most critical issues and opportunities. How about getting permanent change and results together?