【发布时间】:2017-08-03 04:16:43
【问题描述】:
我相信 IMemoryCache 在我的 ASP.NET Core 应用程序中的标准用法。
在 startup.cs 我有:
services.AddMemoryCache();
在我的控制器中,我有:
private IMemoryCache memoryCache;
public RoleService(IMemoryCache memoryCache)
{
this.memoryCache = memoryCache;
}
然而,当我进行调试时,我最终得到了多个内存缓存,每个缓存都有不同的项目。我以为内存缓存会是单例的?
更新了代码示例:
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)));
}
}
如果我在两个不同的浏览器中运行两个客户端,当我点击第二行时,我可以看到 this.memoryCache 包含不同的条目。
【问题讨论】:
-
你是如何测试它的?你能分享更多代码吗?
-
@levent 更新问题
-
我今天在 ASP.NET Core 2 中也看到了这一点。非常不寻常的行为。注入某些控制器的
IMemoryCache实例与注入其他控制器的实例不同。奇怪。 -
啊!但我想要多个
IMemoryCache实例!不同的数据有不同的规则!
标签: c# dependency-injection asp.net-mvc-5.1 memorycache