Why getting multiple instances of IMemoryCache in ASP.Net Core?

南楼画角 提交于 2019-12-21 09:19:15

问题


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

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?

Updated with code sample:

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)));
    }
}

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


回答1:


I did NOT find a reason for this. However, after further reading I swapped from IMemoryCache to IDistributedCache using the in-memory distributed cache and the problem is no longer occurring. I figured going this route would allow me to easily update to a redis server if I needed multiple servers later on.




回答2:


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

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;
}


来源:https://stackoverflow.com/questions/42758705/why-getting-multiple-instances-of-imemorycache-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!