简体   繁体   English

MemoryCache.Default在.NET Core中不可用?

[英]MemoryCache.Default not available in .NET Core?

I'm porting some code from .NET 4.6 til .NET Core and have run into some problems with MemoryCache. 我正在从.NET 4.6到.NET Core移植一些代码,并且遇到了MemoryCache的一些问题。 The 4.6 code is using MemoryCache.Default to instantiate the cache, but this doesn't seem to be available in .NET Core. 4.6代码使用MemoryCache.Default来实例化缓存,但这似乎在.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? 在.NET Core中是否有相同的内容,或者我是否应该将我自己的MemoryCache作为单例创建并通过IOC注入它?

Generally you would use the singleton IMemoryCache 通常你会使用单身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 如果你需要做一些更复杂的东西memoryCacheOptions可以通过注射- IOptions<MemoryCacheOptions>你可以用它

myCustomMemoryCache = new MemoryCache(memoryCacheOptions);

https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory

System.Runtime.Caching.MemoryCache and Microsoft.Extensions.Caching.Memory.MemoryCache are completely different implementations. System.Runtime.Caching.MemoryCache和Microsoft.Extensions.Caching.Memory.MemoryCache是​​完全不同的实现。

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. System.Runtime.Caching.MemoryCache是​​旧版本(4.6),基于ObjectCache,通常通过MemoryCache.Default使用,如您所述。 It actually can be used in .Net Core via the NuGet library in .Net standard format. 它实际上可以通过.Net标准格式的NuGet库在.Net Core中使用。 https://www.nuget.org/packages/System.Runtime.Caching/ 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. Microsoft.Extensions.Caching.Memory.MemoryCache是​​新的.NET核心版本,通常用于较新的ASP核心应用程序。 It implements IMemoryCache and is typically added in the services as described above by @Bogdan 它实现了IMemoryCache,并且通常由@Bogdan在上述服务中添加

https://github.com/aspnet/Extensions/blob/master/src/Caching/Memory/src/MemoryCache.cs https://www.nuget.org/packages/Microsoft.Extensions.Caching.Memory/ https://github.com/aspnet/Extensions/blob/master/src/Caching/Memory/src/MemoryCache.cs https://www.nuget.org/packages/Microsoft.Extensions.Caching.Memory/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM