MemoryCache

MemoryCache

 

To use MemoryCache of Microsoft.Extensions.Caching.Memory:

1)  private readonly IMemoryCache _memoryCache;

      private const string _cacheName = "XXXXCache";

2) , IMemoryCache memoryCache) on constructor's parameters

     and   _memoryCache = memoryCache;

3) Use:

_memoryCache.TryGetValue(_cacheName , out List<StoreMenu>? cacheData);

//Check if cache is missing or empty or time expired, if it is then fetch data

if (cacheData== null || cacheData.Count == 0)
{
...
   if (fetchedCount > 0)
   {
       _memoryCache.Set(_clacheName, cacheData, TimeSpan.FromHours(24));
    }
}
else
{
    storeMenusOfOpenStores = cacheData; // use cache
}

5) Your tests should

IMemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions());

and pass the memory cache to the object.

6) Your dependency configuration should have:

services.AddScoped<IMemoryCache, MemoryCache>();



Comments

Popular posts from this blog

Upgrading to .NET8 from desktop versions 4.8.X

JSON Web Tokens

GHL > Set website so shorter URL address