1

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?

1

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.