Reputation:
i want to use caching in customer controller (Login action)(Nop.Web).
so please help me.
i am using this way but not usefull
create one class in nop.core(domain folder) CustomStoreCache.cs
public partial class CustomStoreCache
{
public ObjectCache StoreCache
{
get
{
return MemoryCache.Default;
}
}
}
and implement cache in customer controller login method and in GetAuthenticatedCustomer() method FormsAuthenticationService.cs
string cachekey = "Id-" + customer.Id.ToString();
var store = CustomStoreCache.StoreCache[cachekey];
but it gives error on this line CustomStoreCache.StoreCache[cachekey];
regards, jatin
Upvotes: 3
Views: 1527
Reputation: 1088
First, you don't need to create a new 'CacheStore', you need to inject the proper cache instance to your controller.
First thing you need to know is that 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.
The default cache is the PerRequestCacheManager and you'll get an instance just by adding it to your controller constructor. If you want to use the static cache, you need to instruct Autofac to inject it when you configure the dependencies for your controller. 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();
You really should use DI instead of adding an static reference to MemoryCacheManager
. This way you could change the cache provider in the future if needed.
I suggest you to use the nopcommerce conventions to access the cache and use this syntax:
return _cacheManager.Get(cacheKey, () =>
{ ..... get and return a brand new instance if not found; } );
There are plenty of examples for this...
Upvotes: 7