本文介绍了为什么要在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实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 04:55