我已在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 ......
}
}
我是否忘记了其他课程中的部分代码?喜欢注册 某人或...... ???
我的错误是什么?
答案 0 :(得分: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();
默认缓存是PerRequestCacheManager,只需将其添加到控制器构造函数中即可获得实例。如果要使用静态缓存,则需要在配置控制器的依赖关系时指示Autofac注入它。
DependencyRegistrar.cs,
builder.RegisterType<MyController>()
.WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"));
你真的应该使用DI而不是向MemoryCacheManager添加静态引用。这样,如果需要,您可以在将来更改缓存提供程序。
答案 1 :(得分:1)
NopCommerce有两个缓存管理器。您正在获取一个在处理相同的http请求时有效的实例,但不会跨越其他请求。
您需要注入静态缓存管理器的实例。您可以在我对其他问题的回复中找到所有信息:Nopcommerce cache seems empty after adding a list。