问题描述
在ASP.NET Core中,非常容易从控制器访问您的内存缓存
In ASP.NET Core its very easy to access your memory cache from a controller
在启动时添加:
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计划任务启动的代码中访问内存缓存?
But, how can I access that same memory cache outside of the controller. eg. I have a scheduled task that gets initiated by HangFire, How do I access the memorycache from within my code that starts via the HangFire scheduled task?
public class ScheduledStuff
{
public void RunScheduledTasks()
{
//want to access the same memorycache here ...
}
}
推荐答案
内存缓存实例可以注入到任何组件中由DI容器控制;这意味着您需要在 ConfigureServices
方法中配置 ScheduledStuff
实例:
Memory cache instance may be injected to the any component that is controlled by DI container; this means that you need configure ScheduledStuff
instance in the ConfigureServices
method:
public void ConfigureServices(IServiceCollection services) {
services.AddMemoryCache();
services.AddSingleton<ScheduledStuff>();
}
,并在ScheduledStuff构造函数中将IMemoryCache声明为依赖项:
and declare IMemoryCache as dependency in ScheduledStuff constructor:
public class ScheduledStuff {
IMemoryCache MemCache;
public ScheduledStuff(IMemoryCache memCache) {
MemCache = memCache;
}
}
这篇关于Asp.Net Core:在控制器外部使用内存缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!