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

I have what I consider the standard use of IMemoryCache in my main ASP.NET application.

In startup.cs, I have:

services.AddMemoryCache();

In my controllers, I have:

private IMemoryCache memoryCache;
public RoleService(IMemoryCache memoryCache)
{
    this.memoryCache = memoryCache;
}

However, when I go into debugging, I get several memory caches with different elements in each. I thought the memory cache would be a single?

Updated with sample code:

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 get to the second line, I see that this.memoryCache contains different entries.

+9
source share
2 answers

. IMemoryCache IDistributedCache, , . , redis, .

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

Source: https://habr.com/ru/post/1672135/


All Articles