如何在启动时将数据放入 MemoryCache? [英] How do I put data in a MemoryCache on startup?
问题描述
在启动时,我想为我的网络应用创建一个静态数据存储.所以我最终偶然发现了 Microsoft.Extensions.Caching.Memory.MemoryCache.构建使用MemoryCache的功能后,突然发现我存储的数据不可用.所以它们可能是两个独立的实例.
At startup, I want to create a store of static data for my web app. So I eventually stumbled onto Microsoft.Extensions.Caching.Memory.MemoryCache. After building the feature that uses the MemoryCache, I suddenly find the data I stored is not available. So they're probably two separate instances.
如何在 Startup 中访问将由我的 Web 应用程序的其余部分使用的 MemoryCache 实例?这就是我目前正在尝试的方式:
How do I access the MemoryCache instance in Startup that will be used by the rest of my web app? This is how I'm currently trying it:
public class Startup
{
public Startup(IHostingEnvironment env)
{
//Startup stuff
}
public void ConfigureServices(IServiceCollection services)
{
//configure other services
services.AddMemoryCache();
var cache = new MemoryCache(new MemoryCacheOptions());
var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove);
//Some examples of me putting data in the cache
cache.Set("entryA", "data1", entryOptions);
cache.Set("entryB", data2, entryOptions);
cache.Set("entryC", data3.Keys.ToList(), entryOptions);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//pipeline configuration
}
}
以及我使用 MemoryCache 的控制器
And the Controller where I use the MemoryCache
public class ExampleController : Controller
{
private readonly IMemoryCache _cache;
public ExampleController(IMemoryCache cache)
{
_cache = cache;
}
[HttpGet]
public IActionResult Index()
{
//At this point, I have a different MemoryCache instance.
ViewData["CachedData"] = _cache.Get("entryA");
return View();
}
}
如果这是不可能的,是否有更好/更简单的替代方案?在这种情况下,全局单例是否可行?
If this is not possible, is there perhaps a better/simpler alternative? Would a global Singleton work in this situation?
推荐答案
添加语句时
services.AddMemoryCache();
您实际上是在说您想要一个内存缓存单例,它可以像在控制器中那样在您注入 IMemoryCache 的任何地方得到解决.因此,您不需要创建新的内存缓存,而是需要向创建的单例对象添加值.您可以通过将 Configure 方法更改为以下内容来执行此操作:
you were in effect saying that you wanted a memory cache singleton that would get resolved wherever you injected IMemoryCache as you did in your controller. So instead of creating a new memory cache, you need to add values to the singleton object that was created. You can do this by changing your Configure method to something like:
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
IMemoryCache cache )
{
var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove);
//Some examples of me putting data in the cache
cache.Set("entryA", "data1", entryOptions);
cache.Set("entryB", data2, entryOptions);
cache.Set("entryC", data3.Keys.ToList(), entryOptions);
//pipeline configuration
}
这篇关于如何在启动时将数据放入 MemoryCache?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!