扩展@Hrvoje Hudo 的答案...
代码:
using System;
using System.Runtime.Caching;
public class InMemoryCache : ICacheService
{
public TValue Get<TValue>(string cacheKey, int durationInMinutes, Func<TValue> getItemCallback) where TValue : class
{
TValue item = MemoryCache.Default.Get(cacheKey) as TValue;
if (item == null)
{
item = getItemCallback();
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(durationInMinutes));
}
return item;
}
public TValue Get<TValue, TId>(string cacheKeyFormat, TId id, int durationInMinutes, Func<TId, TValue> getItemCallback) where TValue : class
{
string cacheKey = string.Format(cacheKeyFormat, id);
TValue item = MemoryCache.Default.Get(cacheKey) as TValue;
if (item == null)
{
item = getItemCallback(id);
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(durationInMinutes));
}
return item;
}
}
interface ICacheService
{
TValue Get<TValue>(string cacheKey, Func<TValue> getItemCallback) where TValue : class;
TValue Get<TValue, TId>(string cacheKeyFormat, TId id, Func<TId, TValue> getItemCallback) where TValue : class;
}
示例
单个项目缓存(当每个项目基于其 ID 进行缓存时,因为缓存项目类型的整个目录会过于密集)。
Product product = cache.Get("product_{0}", productId, 10, productData.getProductById);
缓存所有的东西
IEnumerable<Categories> categories = cache.Get("categories", 20, categoryData.getCategories);
为什么是 TId
第二个助手特别好,因为大多数数据键不是复合的。如果您经常使用复合键,则可以添加其他方法。通过这种方式,您可以避免执行各种字符串连接或 string.Formats 来获取传递给缓存助手的键。它还使传递数据访问方法更容易,因为您不必将 ID 传递给包装器方法……对于大多数用例来说,整个事情变得非常简洁和一致。