C# 在nopCommerce插件中使用CacheManager
我已经创建了一个C# 在nopCommerce插件中使用CacheManager,c#,caching,nopcommerce,C#,Caching,Nopcommerce,我已经创建了一个nopcommercev3.5插件,并希望在控制器操作下加载一个文本文件,以\u cacheManager,然后在下一个请求中重用它 但是\u cacheManager总是将NULL返回给我请求Key。 这是我代码的一部分: public class AbcController : Controller { private readonly ICacheManager _cacheManager; public AbcController(ICacheMa
nopcommercev3.5插件
,并希望在控制器操作下加载一个文本文件
,以\u cacheManager
,然后在下一个请求中重用它
但是\u 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 ......
}
}
公共类AbcController:控制器
{
专用只读ICacheManager(U cacheManager);
公共ABC控制器(ICacheManager缓存管理器)
{
这是。_cacheManager=cacheManager;
}
公共操作结果测试(字符串标题、字符串标题链接、字符串背景色、字符串文本颜色、字符串时间颜色)
{
尝试
{
//myText在此处始终为空>>:(
var myText=_cacheManager.Get(“myText”);
if(string.IsNullOrEmpty(jsText))
{
string path=HttpContext.Server.MapPath(“~/plugins/Misc.Test/App_Data/text.txt”);
myText=System.IO.File.ReadAllText(路径);
//填充缓存管理器>>
_cacheManager.Set(“myText”,myText,int.MaxValue);
}
//其他代码。。。。。。
}
//其他代码。。。。。。
}
}
- 我会忘记其他类中的一些代码吗?比如register 某人或
- 我犯了什么错
您需要插入静态缓存管理器的实例。您可以在我对另一个问题的回答中找到所有信息:。NopCommerce有两个缓存管理器。它们都在DependencyRegistrator.cs中声明:
builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_static").SingleInstance();
builder.RegisterType<PerRequestCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_per_request").InstancePerHttpRequest();
builder.RegisterType().As().Named(“nop_cache_static”).SingleInstance();
builder.RegisterType().As().Named(“nop_cache_per_request”).InstancePerHttpRequest();
默认缓存是PerRequestCacheManager,只需将其添加到控制器构造函数中即可获得实例。如果要使用静态缓存,则需要在配置控制器的依赖项时指示Autofac将其插入
DependencyRegistrator.cs
builder.RegisterType<MyController>()
.WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static"));
builder.RegisterType()
.WithParameter(ResolvedParameter.forName(“nop_cache_static”);
您确实应该使用DI,而不是向MemoryCacheManager添加静态引用。这样,您可以在将来根据需要更改缓存提供程序。感谢您重新编写我以前的答案!在NopCommerce中不需要与DI接口。您应该在IPlugin构造函数中提供IStaticCache参数,以获得一个例子。