C# Asp.Net内核:在控制器外部使用内存缓存
在ASP.NET内核中,从控制器访问内存缓存非常容易C# Asp.Net内核:在控制器外部使用内存缓存,c#,asp.net,asp.net-core,.net-core,memorycache,C#,Asp.net,Asp.net Core,.net Core,Memorycache,在ASP.NET内核中,从控制器访问内存缓存非常容易 [Route("api/[controller]")] public class MyExampleController : Controller { private IMemoryCache _cache; public MyExampleController(IMemoryCache memoryCache) { _cache = memoryCache; } [HttpGet(
[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);
}
}
在启动中,您添加:
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计划任务启动的代码中访问memorycache
public class ScheduledStuff
{
public void RunScheduledTasks()
{
//want to access the same memorycache here ...
}
}
内存缓存实例可以注入到由DI容器控制的任何组件中;这意味着您需要在
ConfigureServices
方法中配置ScheduledStuff
实例:
public void ConfigureServices(IServiceCollection services) {
services.AddMemoryCache();
services.AddSingleton<ScheduledStuff>();
}
我来晚了一点,但我只是想补充一点,以节省别人的时间。您可以通过应用程序中的任何位置的HttpContext访问IMemoryCache
var cache = HttpContext.RequestServices.GetService<IMemoryCache>();
另一种非常灵活和简单的方法是使用
System.Runtime.Caching/MemoryCache
System.Runtime.Caching/MemoryCache:这与以前的ASP.NETMVC的
HttpRuntime.Cache
非常相似您可以在ASP.Net CORE上使用它,而无需任何依赖项注入,也可以在您想要的任何类中使用它。以下是如何使用它:
// First install 'System.Runtime.Caching' (NuGet package)
// Add a using
using System.Runtime.Caching;
// To get a value
var myString = MemoryCache.Default["itemCacheKey"];
// To store a value
MemoryCache.Default["itemCacheKey"] = myString;
非常感谢你的帮助。现在的问题是,如何启动RunScheduledTasks方法?它需要memoryCache参数。错误CS7036未给出与“ScheduledStuff.ScheduledStuff(IMemoryCache)”的必需形式参数“memoryCache”对应的参数
ScheduledStuff ScheduledStuff=new ScheduledStuff()
您不应该在代码中创建ScheduledStuff
实例,相反,您需要从DI容器中获取它-通过在Controller中将其定义为依赖项,或使用HttpContext.RequestServices
。使用HttpContext.RequestServices.GetService()时获取错误:非静态字段、方法或属性需要对象引用。
// First install 'System.Runtime.Caching' (NuGet package)
// Add a using
using System.Runtime.Caching;
// To get a value
var myString = MemoryCache.Default["itemCacheKey"];
// To store a value
MemoryCache.Default["itemCacheKey"] = myString;