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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ASP.Net MVC Script Bundle导致404
- DevExpress v17.2新版亮点—ASP.NET篇(三)
- Asp.Net MVC路由表和控制器操作
- asp.net-mvc – 预编译Hogan.js模板服务器端ASP.NET MVC
- 在ASP.NET页面上显示XML
- asp.net – 如何在使用Html.TextAreaFor时更改字体和颜色?
- asp.net – 在Application_Error中将异常转换为HTTP 404响应
- AutoMapper系列:介绍、使用
- asp.net-mvc – ASP.NET MVC – HTTP验证提示
- asp.net – 我的URL中的这些随机字符是什么?它们是如何实现