Friday, July 9, 2021

Blazor cache management using IMemoryCache

Hi Guys, In depth article about Blazor caching can be found here. We here, will look how to implement it.

Suppose you have a service called CardService that delivers a set of card objects as requested. So we need to cache the data on that methods. Let's see how we can do it.

Here we use the IMemoryCache interface in CardService constructor.

     private IMemoryCache _memoryCache;  
     public CardService(IMemoryCache memoryCache)  
     {  
       _memoryCache = memoryCache;        
     }  

Now we can use the _memoryCache to deal with the cache as below;

     public Task<Keyword[]> GetCardSimilarAskKeywords(string url,string tablePrefix)  
     {  
       string key = "GetCardSimilarAskKeyword"+ url;  //cache key
       var encodedCache = _memoryCache.Get(key);  //get value 
       if (encodedCache == null)  // if value null then get it from DB
       {  
         var options = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromDays(365)).SetAbsoluteExpiration(TimeSpan.FromDays(365));  
         List<Keyword> caList = new List<Keyword>();  
         //Get Keyword list from the data of yours.  
         _memoryCache.Set(key, caList, options);  
         GC.Collect();  
         return Task.FromResult(caList.ToArray());  
       }  
       else  
       {  //if value is in cache, convert and return
         var o = _memoryCache.Get(key);  
         IEnumerable e = o as IEnumerable;  
         var ka = e.OfType<Keyword>().ToList();  
         GC.Collect();  
         return Task.FromResult(ka.ToArray());  
       }  
     }  

In your razor page, inject the service on top

 @inject CardService service  

And now we use the method,

 var kwd = await service.GetCardSimilarAskKeywords("url","prefix");  

Now you need to add the following code to the startup.cs

 services.AddSingleton<CardService>();  

It's done. Lets look at some important options of "MemoryCacheEntryOptions"

We can set the expiration of cache as below;

// keep item in cache as long as it is requested at least
// once every 5 minutes...
// but in any case make sure to refresh it every hour
new MemoryCacheEntryOptions()
  .SetSlidingExpiration(TimeSpan.FromMinutes(5))
  .SetAbsoluteExpiration(TimeSpan.FromHours(1))

In above example, I have set the cache expiration to 365 days. Which means it will recycle once a year. 

Hope you can enjoy the coding...

Anything to know? Post a comment. Thanks.

No comments:

Post a Comment