如何在启动时将数据放入MemoryCache?

Sim*_*eke 7 asp.net-core-mvc .net-core asp.net-core

在启动时,我想为我的Web应用程序创建一个静态数据存储.所以我最终偶然发现了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
    }
}
Run Code Online (Sandbox Code Playgroud)

以及我使用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果这是不可能的,是否有更好/更简单的替代方案?全球Singleton会在这种情况下工作吗?

Gle*_*lls 15

添加语句时

services.AddMemoryCache();
Run Code Online (Sandbox Code Playgroud)

你实际上是说你想要一个内存缓存单例,只要你在控制器中注入了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
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您想使用异步调用填充缓存怎么样?我认为我们不能在配置方法中做到这一点。 (2认同)

Dmi*_*try 6

Use Configure method, not ConfigureServices:

public void Configure(IApplicationBuilder app, IMemoryCache cache, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    cache.Set(...);
}
Run Code Online (Sandbox Code Playgroud)