如果可能的話 - cache ViewResults。更簡單,更好。
對於原始緩存,我使用這個和它的作品如預期(翻過多個請求)=>
public static class CacheManager
{
public static bool Exists
(string cacheKey, HttpContextBase context)
{
return context.Cache[cacheKey] != null;
}
public static object Get
(string cacheKey, HttpContextBase context)
{
return context.Cache[cacheKey];
}
public static T Get<T>
(string cacheKey, HttpContextBase context)
where T : class
{
return context.Cache.Get(cacheKey) as T;
}
public static T Get<T>
(string cacheKey, HttpContextBase context, Func<T> getItemCallback)
where T : class
{
T item = Get<T>(cacheKey, context);
if (item == null) {
item = getItemCallback();
//by default - caching for 1 day
if (item!=null)
context.Cache.Insert(cacheKey, item, null,
DateTime.Now.AddDays(1),TimeSpan.Zero);
}
return item;
}
public static void Save<T>
(string cacheKey, HttpContextBase context, T value)
where T : class
{
context.Cache.Insert(cacheKey, value);
}
}
用法=>
public IList<Database> AllDatabases
{
get
{
return CacheManager.Get
(CacheKeys.AllDatabases, ControllerContext.HttpContext,
() => databaseRepository.GetAll());
}
}
只是 - 我相信,通過上下文基地不必要的複雜
By HttpContext.Current.Cache [「ID」]你的意思是HttpContext.Current.Cache [ID](第一行)?否則,這是您的代碼中的錯誤。 – 2010-02-23 10:27:00
這意味着HttpContext.Current.Cache [編號] – 2010-02-23 12:27:18