I'm porting some code from .NET 4.6 til .NET Core and have run into some problems with MemoryCache. The 4.6 code is using MemoryCache.Default to instantiate the cache, but this doesn't seem to be available in .NET Core. Is there any equivalent to this in .NET Core or should I rather new up my own MemoryCache as a singleton and inject it via IOC?
-
5It is rather a bit more than that, the entire System.Runtime.Caching namespace is missing in .NETCore. That's how it got to be "core", you only ever get a lean small version of .NET by removing stuff. Lots of alternatives available at Nuget.org – Hans Passant Nov 20 '15 at 10:49
-
1Yes, but there is a different implementation of MemoryCache in .NET Core located in Microsoft.Framework.Caching.Memory. I've rewritten the code to use this implementation but it does not have the exact same API and the MemoryCache.Default property does not exist. I guess I'll just have to roll my own :) – henningst Nov 20 '15 at 12:10
2 Answers
System.Runtime.Caching.MemoryCache and Microsoft.Extensions.Caching.Memory.MemoryCache are completely different implementations.
They are similar but have different sets of issues/caveats.
The System.Runtime.Caching.MemoryCache is the older version (4.6) and is based on ObjectCache and is typically used via MemoryCache.Default as you described. It actually can be used in .Net Core via the NuGet library in .Net standard format. https://www.nuget.org/packages/System.Runtime.Caching/
The Microsoft.Extensions.Caching.Memory.MemoryCache is the new .NET core version and is generally used in newer ASP core applications. It implements IMemoryCache and is typically added in the services as described above by @Bogdan
https://github.com/aspnet/Extensions/blob/master/src/Caching/Memory/src/MemoryCache.cs https://www.nuget.org/packages/Microsoft.Extensions.Caching.Memory/

- 1,061
- 13
- 15
Generally you would use the singleton IMemoryCache
IServiceProvider ConfigureServices(IServiceCollection services){
...
services.AddMemoryCache();
...
}
but you can also create the cache
mycache = new MemoryCache(memoryCacheOptions)
If you need to do some more complex stuff
memoryCacheOptions
can be injected through - IOptions<MemoryCacheOptions>
and you can use it
myCustomMemoryCache = new MemoryCache(memoryCacheOptions);
https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory

- 1,323
- 15
- 15
-
I assume you mean `services.AddMemoryCache();` regarding the "singleton `IMemoryCache`"? – user247702 Jul 10 '18 at 09:35
-
1yes => IServiceProvider ConfigureServices(IServiceCollection services){ services.AddMemoryCache(); } – Bogdan Jul 10 '18 at 20:40
-
create cache for non web code like this: MemoryCache Cache = new MemoryCache(Options.Create
(new MemoryCacheOptions())); – Milan Raval Jun 01 '23 at 17:55