【问题标题】:Why getting multiple instances of IMemoryCache in ASP.Net Core?为什么要在 ASP.Net Core 中获取多个 IMemoryCache 实例?
【发布时间】:2017-08-03 04:16:43
【问题描述】:

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

在 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 包含不同的条目。

【问题讨论】:

  • 你是如何测试它的?你能分享更多代码吗?
  • @levent 更新问题
  • 我今天在 ASP.NET Core 2 中也看到了这一点。非常不寻常的行为。注入某些控制器的IMemoryCache 实例与注入其他控制器的实例不同。奇怪。
  • 啊!但我想要多个IMemoryCache 实例!不同的数据有不同的规则!

标签: c# dependency-injection asp.net-mvc-5.1 memorycache


【解决方案1】:

多次创建 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;
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-10-23
      • 1970-01-01
      • 2018-01-05
      • 1970-01-01
      • 2018-06-09
      • 2019-09-30
      • 2018-04-05
      • 2019-04-12
      • 2017-07-02
      相关资源
      最近更新 更多