【发布时间】:2016-11-30 13:57:53
【问题描述】:
在启动时,我想为我的网络应用创建一个静态数据存储。所以我最终偶然发现了 Microsoft.Extensions.Caching.Memory.MemoryCache。在构建了使用 MemoryCache 的功能后,我突然发现我存储的数据不可用。所以它们可能是两个独立的实例。
如何在 Startup 中访问将由我的 Web 应用程序的其余部分使用的 MemoryCache 实例?这就是我目前正在尝试的方式:
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 的控制器
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();
}
}
如果这不可能,是否有更好/更简单的选择?在这种情况下,全局单例是否可以工作?
【问题讨论】:
标签: asp.net-core asp.net-core-mvc .net-core