Search code examples
c#caching.net-corememorycache

how to use MemoryCache Class to cache and get a list in asp.net core


I can get a cached object by creating an instance of IMemoryCache class like this:

_memoryCache.Get<Users>(id);
  1. How can I get a list of Users using this class?

  2. How do I cache the list if it was not cached?


Solution

  • You can use the TryGetValue method that returns the cached object as an output parameter. Refer the example below:-

    List<User> users;
    string key = "usersCacheKey";
    //TryGetValue will get the item from cache and assign it to users variable.
    //It will return false if item is not found.
    if(!_memoryCache.TryGetValue<List<User>>(key, out users){
      //item not found in cache. set the cache item here
      users = new List<User>();
      _memoryCache.Set<List<User>>(key, users);
    }
    

    Reference below link(s) fro more information on how to use Memory Caching in ASP.NET Core 5.0:- Cache in-memory in ASP.NET Core