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

Jef*_*lts 9 c# dependency-injection memorycache asp.net-mvc-5.1

我认为我的ASP.NET核心应用程序中的IMemoryCache的标准用法.

在startup.cs我有:

services.AddMemoryCache();
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我有:

private IMemoryCache memoryCache;
public RoleService(IMemoryCache memoryCache)
{
    this.memoryCache = memoryCache;
}
Run Code Online (Sandbox Code Playgroud)

然而,当我进行调试时,我最终得到了多个内存缓存,每个缓存中包含不同的项目.我以为内存缓存会是单身?

更新了代码示例:

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)));
    }
}
Run Code Online (Sandbox Code Playgroud)

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

too*_*too 6

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;
}
Run Code Online (Sandbox Code Playgroud)


Jef*_*lts 1

我没有找到原因。然而,在进一步阅读后,我使用内存中的分布式缓存从 IMemoryCache 交换到 IDistributedCache,问题不再发生。我认为如果我以后需要多个服务器,走这条路线可以让我轻松更新到 Redis 服务器。