【问题标题】:MemoryCache.Default.AddOrGetExisiting returns null although the key is in the cache尽管键在缓存中,但 MemoryCache.Default.AddOrGetExisiting 返回 null
【发布时间】:2018-03-09 14:11:41
【问题描述】:

我正在为我的 asp.net Web API 应用程序编写单元测试,其中一个正在尝试验证 AddOrGetExisting 是否正常工作。根据 MSDN 文档,AddOrGetExisting 如果已保存,则返回一个项目,否则应将其写入缓存。

我遇到的问题是,如果我从单元测试中将键添加到 MemoryCache 对象,然后调用 AddOrGetExisting,它将始终返回 null 并覆盖该值,而不是返回已保存的值。在调用 AddOrGetExisting(bool isIn 计算结果为 true)之前,我正在验证该值是否在缓存中。

这是我的内存缓存的代码和测试方法。任何帮助将不胜感激:

public static class RequestCache
{
    public static TEntity GetFromCache<TEntity>(string key, Func<TEntity> valueFactory) where TEntity : class
    {
        ObjectCache cache = MemoryCache.Default;
        var newValue = new Lazy<TEntity>(valueFactory);
        CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(60) };
        bool isIn = cache.Contains(key);
        // Returns existing item or adds the new value if it doesn't exist
        var value = cache.AddOrGetExisting(key, newValue, policy) as Lazy<TEntity>;
        return (value ?? newValue).Value;
    }

}

    public string TestGetFromCache_Helper()
    {
        return "Test3and4Values";
    }

    [TestMethod]
    public void TestGetFromCache_ShouldGetItem()
    {
        ObjectCache cache = MemoryCache.Default;
        CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(60) };
        var cacheKey = "Test3";
        var expectedValue = "Test3Value";
        cache.AddOrGetExisting(cacheKey, expectedValue, policy);

        var result = Models.RequestCache.GetFromCache(cacheKey,
            () =>
                {
                    return TestGetFromCache_Helper();
                 });

        Assert.AreEqual(expectedValue, result);
    }

【问题讨论】:

    标签: asp.net .net caching asp.net-web-api2 memorycache


    【解决方案1】:

    问题可能是您在RequestCache.GetFromCache 中将Lazy&lt;TEntity&gt; 作为newValue 传递,但在测试方法中将string 作为expectedValue 传递。

    运行测试时,cache.Contains(key) 确认该键存储了一个值,这是真的。但是它是string 而不是Lazy&lt;TEntity&gt;。显然AddOrGetExisting 决定在这种情况下覆盖该值。

    针对这种特殊情况的解决方法可能是将测试中的 expectedValue 分配调整为如下所示:

    var expectedValue = new Lazy<string>(TestGetFromCache_Helper);
    

    您还需要在测试的最终相等比较中从 Lazy 中提取值,例如:

    Assert.AreEqual(expectedValue.Value, result);
    

    【讨论】:

    • 谢谢!这正是问题所在。如果将来有人遇到同样的问题,只需进行一次编辑:而不是调用 new Lazy(TestGetFromCache_Helper),因为这将返回相同的值并通过测试,无论它是否被覆盖,我创建了第二个返回“Test3Value”的辅助函数,然后调用 new Lazy(TestGetFromCache_Helper2)
    猜你喜欢
    • 2016-03-22
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 2012-04-12
    相关资源
    最近更新 更多