gpt4 book ai didi

c# - 在 nopCommerce 插件中使用 CacheManager

转载 作者:行者123 更新时间:2023-11-30 20:23:45 24 4
gpt4 key购买 nike

我已经创建了一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com