【问题标题】:How do I put data in a MemoryCache on startup?如何在启动时将数据放入 MemoryCache?
【发布时间】: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


    【解决方案1】:

    当你添加语句时

    services.AddMemoryCache();
    

    您实际上是在说您想要一个内存缓存单例,无论您在控制器中注入 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
    }
    

    【讨论】:

    • 如果你想用异步调用填充缓存怎么样。我认为我们不能在 Configure 方法中做到这一点。
    【解决方案2】:

    使用Configure 方法,而不是ConfigureServices

    public void Configure(IApplicationBuilder app, IMemoryCache cache, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        cache.Set(...);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-02
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      • 2011-09-23
      相关资源
      最近更新 更多