如何在Nop330中使用缓存

3 nopcommerce

我想在客户控制器(登录操作)(Nop.Web)中使用缓存.

所以请帮帮我.

我正在使用这种方式,但没有用

create one class in nop.core(domain folder) CustomStoreCache.cs

 public partial class CustomStoreCache
    {
        public ObjectCache StoreCache
        {
            get
            {
                return MemoryCache.Default;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

并在客户控制器登录方法和GetAuthenticatedCustomer()方法FormsAuthenticationService.cs中实现缓存

string cachekey = "Id-" + customer.Id.ToString();
var store = CustomStoreCache.StoreCache[cachekey];
Run Code Online (Sandbox Code Playgroud)

但是它在这行上给出了错误CustomStoreCache.StoreCache [cachekey];

问候,贾丁

Mar*_*ira 7

首先,您不需要创建新的"CacheStore",您需要将适当的缓存实例注入控制器.

您需要知道的第一件事是NopCommerce有两个缓存管理器.两者均声明于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();
Run Code Online (Sandbox Code Playgroud)

默认缓存管理器仅保存当前HTTP请求的数据.第二个是静态缓存,它跨越其他HTTP请求.

默认缓存是PerRequestCacheManager,只需将其添加到控制器构造函数中即可获得实例.如果要使用静态缓存,则需要在配置控制器的依赖关系时指示Autofac注入它.看看DependencyRegistrar.cs,有几个例子,例如:

builder.RegisterType<ProductTagService>().As<IProductTagService>()
            .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"))
            .InstancePerHttpRequest();
Run Code Online (Sandbox Code Playgroud)

你真的应该使用DI而不是添加静态引用MemoryCacheManager.这样,您可以在将来根据需要更改缓存提供程序.

我建议您使用nopcommerce约定来访问缓存并使用以下语法:

return _cacheManager.Get(cacheKey, () =>
        { ..... get and return a brand new instance if not found; } );
Run Code Online (Sandbox Code Playgroud)

这有很多例子......