【发布时间】:2019-11-21 11:03:56
【问题描述】:
我已经按照这个教程https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-2.2
它使用依赖注入使IMemoryCache 仅在特定控制器中可用,例如
public class TController : ControllerBase
{
public IConfiguration Configuration { get; }
private IMemoryCache _cache;
public TController(IConfiguration configuration, IMemoryCache memoryCache)
{
Configuration = configuration;
_cache = memoryCache;
}
public IActionResult GetAccessToken()
{
string key ="IDGKey";
string obj;
if (!cache.TryGetValue<string>(key, out obj))
{
obj = DateTime.Now.ToString();
_cache.Set<string>(key, obj);
}
return obj;
}
}
现在,如果我尝试访问同一命名空间或不同控制器中的 _cache 值
public class RController : ControllerBase
{
public IActionResult R()
{
var cb = _cache.Get("IDGKey");
return Ok(cb);
}
}
它给出了以下错误 -
当前上下文中不存在名称“_cache”(CS0103)
如何使它 _cache 对所有控制器可用?
【问题讨论】:
标签: asp.net-mvc asp.net-core caching asp.net-core-mvc asp.net-core-2.0