.NET Core gives you 2 options to use as cache data in memory. Either you use the System.Runtime.Caching/MemoryCache (NuGet package) or the Microsoft.Extensions.Caching.Memory/IMemoryCache.
The latter is recommended over System.Runtime.Caching
/MemoryCache
because it's better integrated into ASP.NET Core. For example, IMemoryCache
works natively with ASP.NET Core dependency injection. Use System.Runtime.Caching
/MemoryCache
only as a compatibility bridge when porting code from ASP.NET 4.x to ASP.NET Core.
The memory cache can be registered in ASP.NET Core through the AddMemoryCache extension method.
I was looking at a way to clear the cache. However I noticed there wasn’t an appropriate method available when I took a look at the IMemoryCache interface:
A search on the Internet brought me to the following suggested solution:
This is not a good idea because it will iterate over all keys. Why? Take a look at the following remark in the documentation:
Retrieving an enumerator for a MemoryCache instance is a resource-intensive and blocking operation. Therefore, the enumerator should not be used in production applications.
A better solution is to use the Compact method available on the MemoryCache instance:
Remark: This of course only works when your IMemoryCache implementation is based on the MemoryCache class.