1

我使用ObjectCache 的MemoryCache.Default实例在 MVC 应用程序中存储数据;每次我保存一些项目而不是立即阅读它时,我都会看到项目按预期存储。但是当创建 Cashing 类的新实例(我的意思是使用 ObjectCache 的类)时,我无法访问旧值。我已经实现了单例只保留ObjectCache 的一个实例,但这对我没有帮助。

//here is single instance of caching object
public class CacheSingleton
{
    private static CacheSingleton instance;

    private CacheSingleton() { cache = MemoryCache.Default; }

    public static CacheSingleton Instance
    {
        get 
        {
            if (instance == null)
            {
                instance = new CacheSingleton();
            }
            return instance;
        }
    }

    public ObjectCache cache { get; private set; }
}


    // and here is piece of caching class 
    .........
    private ObjectCache cache;


    public DefaultCacheProvider()
    {
        cache = CacheSingleton.Instance.cache;
    }

    public object Get(string key)
    {
        return cache[key];
    }

    public void Set(string key, object data, int cacheTime, bool isAbsoluteExpiration)
    {
        CacheItemPolicy policy = new CacheItemPolicy();
        if (isAbsoluteExpiration)
        {
            policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);
        }
        else
        {
            policy.SlidingExpiration = TimeSpan.FromMinutes(cacheTime);
        }

        cache.Add(new CacheItem(key, data), policy);
    }

    public bool IsSet(string key)
    {
        return (cache[key] != null);
    }

    public void Invalidate(string key)
    {
        cache.Remove(key);
    }

任何人都可以解释为什么缓存类的每个新实例(最后一个代码)我无法访问旧值。谢谢。

4

0 回答 0