c# - 在 nopCommerce 插件中使用 CacheManager

标签 c# caching nopcommerce

我已经创建了一个 nopCommerce v3.5 插件,并希望在 Controller Action 下加载一个文本文件_cacheManager 然后在下一个中重用它请求。

但是 _cacheManager 总是为我的请求 Key 返回 NULL

这是我的部分代码:

public class AbcController : Controller   
{
    private readonly ICacheManager _cacheManager;

    public AbcController(ICacheManager cacheManager)
    {
        this._cacheManager = cacheManager;
    }

    public ActionResult Test(string title,string titleLink, string backColor,  string textColor, string timeColor)
    {
        try
        {
           // myText is always NULL here >>   :(
           var myText = _cacheManager.Get<string>("myText");

           if (string.IsNullOrEmpty(jsText))
           {
              string path = HttpContext.Server.MapPath("~/plugins/Misc.Test/App_Data/text.txt");
              myText = System.IO.File.ReadAllText(path);

              // Fill cacheManager >> 
              _cacheManager.Set("myText", myText, int.MaxValue);
            }

            // Other codes ......
        }

        // Other codes ......
     }
}
  • 我是否忘记了其他类中的某些代码?喜欢注册 某人或...???

  • 我的错误是什么?

最佳答案

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();

默认缓存是 PerRequestCacheManager,您只需将其添加到 Controller 构造函数中即可获得一个实例。如果要使用静态缓存,则需要在为 Controller 配置依赖项时指示 Autofac 注入(inject)它。

DependencyRegistrar.cs,

builder.RegisterType<MyController>()
                .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"));

你真的应该使用 DI 而不是添加对 MemoryCacheManager 的静态引用。这样您以后就可以根据需要更改缓存提供程序。

关于c# - 在 nopCommerce 插件中使用 CacheManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28152005/

相关文章:

asp.net - NopContext.Current.User 始终为 null

c# - 从接口(interface)转换到类,糟糕的设计还是小违规?

android - 以编程方式将文件从缓存目录 move 到 SDCard

caching - CakePHP 页面偶尔丢失布局 - 帮助?

java - 当spring调用get(Object o, Class<T> aClass)函数时使用@Cacheable

c# - 需要将 Controller 的操作方法调用到 c# mvc 中的另一个类中

c# - ASP.NET 在另一个客户端上更新 UpdatePanel

c# - If 语句跳过 for 循环中除第一个元素之外的元素。我怎样才能为其他元素找到正确的解决方案?

c# - VS 设计器中是否有删除事件的方法?

c# - 我如何从我的 nopCommerce 商店接收付款?