what is caching : Caching is the process of storing the data that’s frequently used so that data can be served faster for any future requests.
why IMemoryCach: Suppose we have a very lightweight process which talks to another server whose data is not going to change frequently , so we can use memory cach in this case. Without any caching in place, we would be making multiple requests which will ultimately result in timeouts or making the remote server unnecessarily busy.
How we can use it in .net: First, we need to inject the in-memory caching service into the constructor of the our class , like this :
public class HomeController : Controller { private readonly IMemoryCache _cache; public HomeController(ILogger<HomeController> logger, IMemoryCache memoryCache) { _cache = memoryCache; }
now we want to cache the response of the API.
// Code removed for brevity ... // Look for cache key. if (!_cache.TryGetValue(CacheKeys.Entry, out cacheEntry)) { // Key not in cache, so get data. cacheEntry = DateTime.Now; // Set cache options. var cacheEntryOptions = new MemoryCacheEntryOptions() // Keep in cache for this time, reset time if accessed. .SetSlidingExpiration(TimeSpan.FromSeconds(3)); // Save data in cache. _cache.Set(CacheKeys.Entry, cacheEntry, cacheEntryOptions); }