问题
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?
回答1:
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://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory
回答2:
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/
来源:https://stackoverflow.com/questions/33822333/memorycache-default-not-available-in-net-core