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.
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.