为什么要在ASP.Net Core中获取多个IMemoryCache实例?

编程入门 行业动态 更新时间:2024-10-26 19:30:21
本文介绍了为什么要在ASP.Net Core中获取多个IMemoryCache实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我相信我的ASP.NET Core应用程序中有IMemoryCache的标准用法。

I have what I believe is a standard usage of IMemoryCache in my ASP.NET Core application.

在startup.cs中,我有:

In startup.cs I have:

services.AddMemoryCache();

在我的控制器中,我有:

In my controllers I have:

private IMemoryCache memoryCache; public RoleService(IMemoryCache memoryCache) { this.memoryCache = memoryCache; }

但是,当我进行调试时,最终会得到多个具有不同每个项目。我以为内存缓存将是一个单例?

Yet when I go through debug, I end up with multiple memory caches with different items in each one. I thought memory cache would be a singleton?

已更新代码示例:

public List<FunctionRole> GetFunctionRoles() { var cacheKey = "RolesList"; var functionRoles = this.memoryCache.Get(cacheKey) as List<FunctionRole>; if (functionRoles == null) { functionRoles = this.functionRoleDAL.ListData(orgId); this.memoryCache.Set(cacheKey, functionRoles, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromDays(1))); } }

如果我在两个不同的浏览器中运行两个客户端,当我点击第二行,可以看到this.memoryCache包含不同的条目。

If I run two clients in two different browsers, when I hit the second line I can see this.memoryCache contains different entries.

推荐答案

多次创建IMemoryCache的原因是

The reason that IMemoryCache is created multiple times is that your RoleService most likely gets scoped dependencies.

要修复此问题,只需添加一个包含内存缓存的新单例服务并在需要时插入,而不是IMemoryCache:

To fix it simply add a new singleton service containing the memory cache and inject in when needed instead of IMemoryCache:

// Startup.cs: services.AddMemoryCache(); services.AddSingleton<CacheService>(); // CacheService.cs: public IMemoryCache Cache { get; } public CacheService(IMemoryCache cache) { Cache = cache; } // RoleService: private CacheService cacheService; public RoleService(CacheService cacheService) { this.cacheService = cacheService; }

更多推荐

为什么要在ASP.Net Core中获取多个IMemoryCache实例?

本文发布于:2023-11-13 21:41:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585394.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   要在   实例   ASP   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!