[英]Get all cache in ASP.NET Core 1
The version is rc1. 版本是rc1。 In my old project there are codes like 在我的旧项目中,有类似的代码
System.Web.Caching.Cache c = System.Web.HttpRuntime.Cache;
System.Collections.IDictionaryEnumerator cacheEnumerator = c.GetEnumerator();
while (cacheEnumerator.MoveNext())
{....}
In core 1 I use IMemoryCache
and I can get cache by key like 在核心1中我使用IMemoryCache
,我可以通过键获得缓存
var c = this._memoryCache;
var data = c.Get("data");
I want to make a view to list all cache. 我想创建一个列出所有缓存的视图。 How can I get all cache in Core 1? 如何在Core 1中获取所有缓存?
Looking at the source of ASP.NET Core's MemoryCache implementation on github , you can see that the class doesn't expose any functionality to scan or iterate the list of cache entries. 在github上查看ASP.NET Core的MemoryCache实现的源代码,您可以看到该类没有公开任何扫描或迭代缓存条目列表的功能。
The closest you can do is use reflection to read the inner cache dictionary: 您最接近的是使用反射来读取内部缓存字典:
private readonly Dictionary<object, CacheEntry> _entries;
Wrap the reflection code in an extension method that accepts an IMemoryCache
and returns an IEnumerable<CacheEntry>
and you're good - but there are several risks involved: 将反射代码包装在一个接受IMemoryCache
的扩展方法中并返回一个IEnumerable<CacheEntry>
并且你很好 - 但是涉及到几个风险:
IMemoryCache
. 这特定于Microsoft.Extensions.Caching.Memory.MemoryCache的实现,它只是IMemoryCache
一个实现。 You might replace it with a different implementation one day, which will break. 您可能有一天会用不同的实现替换它,这将会破坏。 IMemoryCache
's methods, but even then, there's a risk. 第一步是永远不要直接更新缓存条目,并始终通过IMemoryCache
的方法,但即使这样,也存在风险。 Knowing the risks, though, you can go forth and get your job done. 但是,了解风险,您可以前进并完成工作。
Instead of using reflection you could also add to a Dictionary every time you add to the cache and maintain it with callbacks from cache policies. 除了使用反射之外,您还可以在每次添加到缓存时添加到字典中,并使用缓存策略中的回调进行维护。 Less dependent on the .net MemoryCache
if you handle it this way. 如果以这种方式处理它,则更少依赖于.net MemoryCache
。 Would probably have some concurrency issues with the Dictionary, but as long as it is locked on updates and deletes it should do fine. 可能会对Dictionary有一些并发性问题,但只要它在更新和删除时被锁定就应该没问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.