【发布时间】:2017-06-22 07:40:45
【问题描述】:
在 ASP.NET Core 中,从控制器访问内存缓存非常容易
在您的启动中添加:
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
}
然后从你的控制器
[Route("api/[controller]")]
public class MyExampleController : Controller
{
private IMemoryCache _cache;
public MyExampleController(IMemoryCache memoryCache)
{
_cache = memoryCache;
}
[HttpGet("{id}", Name = "DoStuff")]
public string Get(string id)
{
var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromHours(1));
_cache.Set("key", "value", cacheEntryOptions);
}
}
但是,我怎样才能访问控制器外部的相同内存缓存。例如。我有一个由 HangFire 启动的计划任务,如何从通过 HangFire 计划任务启动的代码中访问内存缓存?
public class ScheduledStuff
{
public void RunScheduledTasks()
{
//want to access the same memorycache here ...
}
}
【问题讨论】:
标签: c# asp.net asp.net-core .net-core memorycache