加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 03:36:01 所属栏目:asp.Net 来源:网络整理
导读:在启动时,我想为我的Web应用程序创建一个静态数据存储.所以我最终偶然发现了Microsoft.Extensions.Caching.Memory.MemoryCache.在构建使用MemoryCache的功能之后,我突然发现我存储的数据不可用.所以他们可能是两个独立的实例. 如何在Startup中访问将由我的其
在启动时,我想为我的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
    }
}

以及我使用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();

你实际上是说你想要一个内存缓存单例,只要你在控制器中注入了IMemoryCache就可以得到解决.因此,您需要将值添加到已创建的单例对象,而不是创建新的内存缓存.您可以通过将Configure方法更改为以下内容来执行此操作:

public void Configure(IApplicationBuilder app,ILoggerFactory loggerFactory,IMemoryCache cache )
{
    var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove);

    //Some examples of me putting data in the cache
    cache.Set("entryA",entryOptions);
    cache.Set("entryB",entryOptions);
    cache.Set("entryC",entryOptions);
    //pipeline configuration
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读