如何在IMemoryCache的单独实例中清除cacheKey [英] How to clear cacheKey in separate instance of IMemoryCache

查看:440
本文介绍了如何在IMemoryCache的单独实例中清除cacheKey的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ASP.NET Core 1.1 上运行,在我的 Startup.cs 中,我将策略配置为以及 DistributedMemoryCache ,像这样:

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

我遇到的问题是我要为特定用户删除特定的cacheKey。当用户被添加到新角色时,我然后尝试删除该cacheKey的现有缓存条目(用户名和角色名),然后使用更新的 isInRole值重新添加。但是,当我删除的控制器然后添加新的cacheKey来检查查询是否存在时,它始终返回null。然后,如果我尝试导航到检查用户是否在角色中的页面,该检查仍会显示cacheKey的PREVIOUS值。

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.

我要做什么相信正在发生的事情是,由于我的策略通过了我的 RoleRepo 的一个实例(注入了 IMemoryCache ),因此它最终是一个单独的实例,而不是 services.AddTransient 行中的实例。

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.

如何如何配置它,以便 IMemoryCache 是单例,还是专门将 RoleRepo 的SAME实例传递到 services.AddTransient 行?

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?

这是我的`RoleRepo设置:

Here's my `RoleRepo setup:

private readonly IMemoryCache _memoryCache;

public RoleRepo(IConfigurationRoot configuration, IMemoryCache memoryCache)
    : base(configuration)
{
    _memoryCache = memoryCache;
}


推荐答案

我找到了解决方案问题。由于我正在更新我的RoleRepo,因此我继续进行操作,并以单例方式添加了该实例...

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

这篇关于如何在IMemoryCache的单独实例中清除cacheKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆