【问题标题】:MemoryCache.Default not available in .NET Core?MemoryCache.Default 在 .NET Core 中不可用?
【发布时间】:2016-02-22 16:25:06
【问题描述】:

我正在将一些代码从 .NET 4.6 移植到 .NET Core,但在 MemoryCache 方面遇到了一些问题。 4.6 代码使用 MemoryCache.Default 来实例化缓存,但这在 .NET Core 中似乎不可用。在 .NET Core 中是否有与此等效的方法,或者我是否应该将自己的 MemoryCache 新建为单例并通过 IOC 注入它?

【问题讨论】:

  • 更重要的是,.NETCore 中缺少整个 System.Runtime.Caching 命名空间。这就是它成为“核心”的方式,你只能通过删除东西来获得一个精简的.NET 小版本。 Nuget.org 上有很多替代品
  • 是的,但在 Microsoft.Framework.Caching.Memory 中的 .NET Core 中有不同的 MemoryCache 实现。我已重写代码以使用此实现,但它没有完全相同的 API,并且 MemoryCache.Default 属性不存在。我想我只能自己动手了:)

标签: c# .net dnx memorycache coreclr


【解决方案1】:

System.Runtime.Caching.MemoryCache 和 Microsoft.Extensions.Caching.Memory.MemoryCache 是完全不同的实现。

它们相似,但有不同的问题/注意事项。

System.Runtime.Caching.MemoryCache 是旧版本 (4.6),基于 ObjectCache,通常通过 MemoryCache.Default 使用,如您所述。它实际上可以通过 .Net 标准格式的 NuGet 库在 .Net Core 中使用。 https://www.nuget.org/packages/System.Runtime.Caching/

Microsoft.Extensions.Caching.Memory.MemoryCache 是新的 .NET 核心版本,通常用于较新的 ASP 核心应用程序。它实现了 IMemoryCache,通常由@Bogdan 如上所述添加到服务中

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

【讨论】:

    【解决方案2】:

    通常你会使用单例IMemoryCache

    IServiceProvider ConfigureServices(IServiceCollection services){ 
    ...
     services.AddMemoryCache(); 
    ...
    }
    

    但你也可以创建缓存

    mycache = new MemoryCache(memoryCacheOptions)

    如果你需要做一些更复杂的事情 memoryCacheOptions 可以通过-IOptions<MemoryCacheOptions> 注入,就可以使用了

    myCustomMemoryCache = new MemoryCache(memoryCacheOptions);
    

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

    【讨论】:

    • 我假设您的意思是 services.AddMemoryCache(); 关于“单身IMemoryCache”?
    • yes => IServiceProvider ConfigureServices(IServiceCollection services){ services.AddMemoryCache(); }
    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 2021-09-25
    • 2018-05-15
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    相关资源
    最近更新 更多