-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;
}
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 ?
    – Dimitar
    Oct 2, 2019 at 14:56
  • 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 requests
    – Tseng
    Oct 2, 2019 at 18:53

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.