[英]Why getting multiple instances of IMemoryCache in ASP.Net Core?
我认为我的ASP.NET核心应用程序中的IMemoryCache的标准用法。
在startup.cs我有:
services.AddMemoryCache();
在我的控制器中,我有:
private IMemoryCache memoryCache;
public RoleService(IMemoryCache memoryCache)
{
this.memoryCache = memoryCache;
}
然而,当我进行调试时,我最终得到了多个内存缓存,每个缓存中包含不同的项目。 我以为内存缓存会是单身?
更新了代码示例:
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包含不同的条目。
我没有找到理由。 但是,在进一步阅读后,我使用内存中的分布式缓存从IMemoryCache交换到IDistributedCache,问题不再发生。 如果我以后需要多台服务器,我认为这条路线可以让我轻松更新到redis服务器。
IMemoryCache多次创建的原因是您的RoleService很可能获得作用域依赖项。
要修复它,只需添加一个包含内存缓存的新单例服务,并在需要时注入而不是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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.