问题
I am experiencing a problem with the cacheManager
in NopCommerce
I have a list of nopCommerce products, in the form of an IPagedList<Product>
I add them to my cachemanager as such:
_cacheManager.Set("SearchResult", products.ToList(), 5);
Now whenever i try to retrieve them like this:
var searchresults = new List<Product>();
if (_cacheManager.IsSet("SearchResult"))
{
searchresults = _cacheManager.Get<List<Product>>("SearchResult");
}
It is just empty, like, the isSet evaluates to false
.
I tried to _cacheManager.Clear()
before i add them, but that also doesn't work. I am running out of ideas here. Anyone got a clue?
I used this as a source for the retrieval:
http://www.nopcommerce.com/boards/t/12290/getting-an-item-on-the-cachemanager-requires-a-function-param-.aspx
回答1:
I suppose that the problem is that you can't cache data between http requests, but I'm sure that you can retrieve that data during the same request.
NopCommerce has two cache managers. Both are declared at DependencyRegistrar.cs
:
builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_static").SingleInstance();
builder.RegisterType<PerRequestCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_per_request").InstancePerHttpRequest();
The default cache manager, only holds data for the current HTTP request. The second one, the static cache, spans to other HTTP requests.
If you want to use the static cache, you need to instruct Autofac to inject it when you configure the dependencies for your service. Look at DependencyRegistrar.cs
, there are several examples for this, for instance:
builder.RegisterType<ProductTagService>().As<IProductTagService>()
.WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
.InstancePerHttpRequest();
I encourage you to use this approach instead of adding an static reference to MemoryCacheManager
.
回答2:
I solved it by adding this._cacheManager = new MemoryCacheManager()
instead of
this._cacheManager = cacheManager
, where cachemanager is an instance of ICacheManager
来源:https://stackoverflow.com/questions/23675162/nopcommerce-cache-seems-empty-after-adding-a-list