在nopCommerce插件中使用CacheManager

RAM*_*RAM 2 c# caching nopcommerce

我在Controller Action下创建了一个nopCommerce v3.5 plugin并且想要在下一个请求中重用它.load a text file_cacheManager

_cacheManager总是回复NULL我的要求Key.

这是我的代码的一部分:

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 ......
     }
}
Run Code Online (Sandbox Code Playgroud)
  • 我是否忘记了其他课程中的部分代码?喜欢注册某人或... ???

  • 我的错是什么?

Tus*_*har 5

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)

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

DependencyRegistrar.cs,

builder.RegisterType<MyController>()
                .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"));
Run Code Online (Sandbox Code Playgroud)

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