问题
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;
}
回答1:
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);
来源:https://stackoverflow.com/questions/58203771/how-to-clear-cachekey-in-separate-instance-of-imemorycache