Asp.net mvc 2 在asp.net mvc2中使用企业库缓存应用程序块

Asp.net mvc 2 在asp.net mvc2中使用企业库缓存应用程序块,asp.net-mvc-2,enterprise-library,Asp.net Mvc 2,Enterprise Library,我尝试使用microsoft企业库的缓存应用程序块。我使用了MS Enterprise Library V5.0 这是我在home controller的索引方法中制作的示例代码 Person p = new Person(10, "person1"); ICacheManager cacheMgr = CacheFactory.GetCacheManager("myCache"); ViewData["Message"] = "Welcome t

我尝试使用microsoft企业库的缓存应用程序块。我使用了MS Enterprise Library V5.0

这是我在home controller的索引方法中制作的示例代码

        Person p = new Person(10, "person1");
        ICacheManager cacheMgr = CacheFactory.GetCacheManager("myCache");
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        if (Session["currsession"] != null)
        {
            if (!cacheMgr.Contains(p.pid.ToString()))
            {
                Response.Write("item is not in cache");
                return View(p);
            }
            else
            {
                Response.Write("item is still in cache");
                return View(p);
            }
        }
        else
        {
            Session["currsession"] = 1;
            cacheMgr.Add(p.pid.ToString(), p, CacheItemPriority.High, null, new SlidingTime(TimeSpan.FromSeconds(10)));
            return View(cacheMgr.GetData(p.pid.ToString()));
        }
我在模型中使用的person类只有一个具有2个公共属性的构造函数。没有使用任何特殊功能

现在,这是使用企业库缓存块缓存的正确过程吗。如果没有,我如何才能以高效的方式编写这段代码

另外,我得到的响应是
项仅在延迟20秒后才不在缓存中。代码的实现是否有任何错误,或者缓存背后是否有详细的理论


请建议这种用法的最佳实践

由于您指定了10秒的滑动过期时间,这意味着如果您在重新加载页面之间等待的时间超过10秒,您将得到
项不在缓存中

在会话中首次加载=>无消息
重新加载=>在缓存中
重新加载=>在缓存中
等待10秒钟
重新加载=>不在缓存中

这就是你看到的吗


旧答案:

企业缓存应用程序块可能远远超出您的需要。我最喜欢的缓存是的缓存(只包括FubuCore.dll)。通过使用带有“缺少元素”委托的ConcurrentDictionary,可以获得非常类似的实现。下面是一个例子:

FubuMVC缓存示例:

public class PersonCache
{
    private Cache _Cache = new Cache();

    public PersonCache()
    {
        _Cache.OnMissing = key => MyDatabase.People.GetById(key);
    }

    public Person GetById(int id)
    {
        return _Cache[id];
    }
}

谢谢你的建议。请注意,我的问题是如何在同一会话中的多个页面刷新之间维护缓存。为此,我使用了一个会话变量。这条路对吗。请分析我的代码并给我一个答复。对不起,我想我没有读完这个问题。现在是凌晨2点,所以我没有集中注意力。