Scenario
While trying to implement caching strategy for category page, I found my results and in particular, my FeaturedProducts of the CategoryModel are not being cached while running in debug mode.
As usual, I created my custom controller as follow.
In my controller method, I would check and use the cache if it is available.
As usual, I created my custom controller as follow.
In my controller method, I would check and use the cache if it is available.
Steps In
In debug mode, immediately after the object is written to the cache, the object is in the cache. However, it will ALWAYS return false, and I if I step into the code, the object indeed not in the cache.
This can easily be over-generalised as one of the following without paying closer attention as:-- Cache not working
- Nop is slow
- Performance Issue
Solution
If we look at what nop provides for ICacheManager, there are 2 CacheManagers (We will ignore the NopNullCache for now) that implement ICacheManager, they are MemoryCacheManager (nop_cache_static) and PerRequestCacheManager (nop_cache_per_request).
As the names suggest, MemoryCacheManager writes objects to memory cache; PerRequestCacheManager writes objects to the session on per request bases.
In Nop.Web\Infrastructure\DependencyRegistrar.cs, we found the following piece of code.
Without specifying what to register for ICacheManager in IoC, I found by default the PerRequestCacheManager (nop_cache_per_request) is instantiated.
This is an incorrect behavior for my problem as I want to put the content in the memory cache and made available to multi requests over a period of time (until times out).
We need to tell IoC which type of CacheManager we want to instantiate for the interface by using the following code. This will hint IoC to inject a concrete class of MemoryCacheManager to my ICacheManager!!
I found it useful to give also provide LanguageService & StoreService with the memory cache rather than the per-request, as I noticed SQL queries being run against these tables for every request, which is rather redundant as they hardly change.
ReplyDelete