How to clear cacheKey in separate instance of IMemoryCache
Asked Answered
C

1

-1

I'm running on ASP.NET Core 1.1 where in my Startup.cs I configure Policies, as well as DistributedMemoryCache, like this:

var roleRepo = new RoleRepo(Configuration, new MemoryCache(new MemoryCacheOptions()));

services.Configure<AuthorizationOptions>(options =>
{
    options.AddPolicy("MyPolicy", policy => policy.Requirements.Add(new MyPolicyRoleRequirement(roleRepo)));
});

services.AddDistributedMemoryCache();

//...

services.AddTransient<IRoleRepo, RoleRepo>();

The problem I'm having is I'm trying to remove a specific cacheKey for a specific user. When the user gets added to a new role, I then try to remove the existing cache entry for that cacheKey (username plus rolename), and then re-add with the updated "isInRole" value. But when my controller that removes, then adds the new cacheKey checks to see if the query exists, it always returns null. Then, if I try to navigate to the page that checks whether the user is in the role or not, that check still shows the PREVIOUS value of the cacheKey.

What I believe is going on is that since my policies get passed a single instance of my RoleRepo (which injects IMemoryCache), it ends up being a separate instance vs the one that is DI'd in the services.AddTransient line.

How do I configure this so either the IMemoryCache is a singleton, or specifically pass the SAME instance of my RoleRepo into the services.AddTransient line?

Here's my `RoleRepo setup:

private readonly IMemoryCache _memoryCache;

public RoleRepo(IConfigurationRoot configuration, IMemoryCache memoryCache)
    : base(configuration)
{
    _memoryCache = memoryCache;
}
Caernarvonshire answered 2/10, 2019 at 14:36 Comment(2)
See the method here: github.com/aspnet/Extensions/blob/… and you will see that if succeed it is added as Singleton. Other than that from the code you showed - only guesses can be made. Can you add the code that interacts with cache as well ?Matri
Whats the point of having a transient memory cache? This would just create multiple instances of the cache, which kinda makes it useless since every request, even every resolve would access a different instance of it. the only value of memory cache is if its a singleton and survives the requestsGoahead
C
0

I found a solution to the issue. Since I'm "newing-up" my RoleRepo, I just went ahead and added THAT INSTANCE as a singleton...

services.AddSingleton<IRoleRepo>(roleRepo);
Caernarvonshire answered 2/10, 2019 at 15:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.