gpt4 book ai didi

asp.net-core - 如何在启动时将数据放入 MemoryCache?

转载 作者:行者123 更新时间:2023-12-03 14:01:42 24 4
gpt4 key购买 nike

在启动时,我想为我的网络应用程序创建一个静态数据存储。所以我最终偶然发现了 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 的 Controller
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();
}
}

如果这是不可能的,是否有更好/更简单的选择?在这种情况下,全局 Singleton 会起作用吗?

最佳答案

当您添加语句时

services.AddMemoryCache();

您实际上是在说您想要一个内存缓存单例,无论您在 Controller 中注入(inject) IMemoryCache 的任何地方都可以解析该内存缓存单例。因此,您需要向已创建的单例对象添加值,而不是创建新的内存缓存。您可以通过将 Configure 方法更改为以下内容来做到这一点:
    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
}

关于asp.net-core - 如何在启动时将数据放入 MemoryCache?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40890273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com