【问题标题】:Why is IMemoryCache's TryGetValue throwing an InvalidOperationException?为什么 IMemoryCache 的 TryGetValue 会抛出 InvalidOperationException?
【发布时间】:2018-10-19 21:33:38
【问题描述】:

在我的 Web 应用程序中,我的一项服务使用了注入的 IMemoryCache

public class InternalService
{
    private readonly IMemoryCache m_memoryCache;

    private readonly MemoryCacheEntryOptions m_cacheEntryOptions;

    public Service(IMemoryCache memoryCache)
    {
         m_memoryCache = memoryCache;

         // Set cache options: keep in cache for this time, reset time in 1 hour, no matter what.
        m_cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromHours(1d));
    }
} 

在这项服务中,我使用缓存来避免昂贵的调用。该调用返回一个实体列表:

public class Entity
{
    public long Id {get; set;}    
}

这是Service中处理缓存的方法:

private async IList<Entity> GetEntitiesAsync(string tenantId)
{
    if (false == m_memoryCache.TryGetValue(tenantId, out IList<Entity> tenantEntities) || tenantEntities.Count == 0)
    {
         // Do the expensive call.
         IList<Entity> tenantEntities = await ExpensiveServiceCallAsync(tenantId);

         m_memoryCache.Set(tenantId, tenantEntities , m_cacheEntryOptions);
    }

    return tenantEntities;
}

但是,它确实会引发以下异常:

System.InvalidCastException:无法转换类型的对象 'System.String' 输入 'System.Collections.Generic.IList`1[Entity]'。 在 Microsoft.Extensions.Caching.Memory.CacheExtensions.TryGetValue[TItem](IMemoryCache 缓存、对象键、TItem&值)

如 Microsoft 文档中所述,它表示:

内存缓存可以存储任何对象;分布式缓存 接口仅限于 byte[]。

问题

我做错了什么?当我应该缓存Entity 的列表时,我不明白为什么缓存期望返回string

【问题讨论】:

  • 只是检查一下,在您的构造函数中,您设置了 m_memoryCache 的局部变量,但在您的 GetEntitiesAsync 方法中,您使用了 m_cache。这只是一个错字吗?
  • 我怀疑在您的代码中某处您正在使用与您在此处使用的相同的tenantId 将字符串值添加到缓存中。
  • 正确。这确实只是一个复制粘贴错误。
  • 也许试试 if (false == m_memoryCache.TryGetValue(tenantId, out objecttenantEntities) 看看从缓存中返回了什么
  • 你是对的......我没有意识到我们应用程序中的另一个类正在使用缓存和相同的键来存储自己的信息......原来是另一个字符串。您可以将其发布为答案吗?

标签: c# caching asp.net-core


【解决方案1】:

我怀疑您在代码中的某处将string 值添加到缓存中,并与您在此处使用的tenantId 相同。

请记住,m_memoryCache 实例在您的整个代码中使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 2011-01-10
    • 2020-05-15
    • 1970-01-01
    相关资源
    最近更新 更多