我的一个项目中有类似的要求。我最终做的是创建一个 DataAccesLayer (DAL) 缓存库,我在 DAL 中为我的每个组件继承它。我有一个单独的缓存类来保存缓存。请注意,我所有的对象都有 ID 和名称。您可以根据需要定制基类。
DAL 基类:
public abstract class DALBaseCache<T>
{
public List<T> ItemList
{
get
{
List<T> itemList = DALCache.GetItem<List<T>>(typeof(T).Name + "Cache");
if (itemList != null)
return itemList;
else
{
itemList = GetItemList();
DALCache.SetItem(typeof(T).Name + "Cache", itemList);
return itemList;
}
}
}
/// <summary>
/// Get a list of all the Items
/// </summary>
/// <returns></returns>
protected abstract List<T> GetItemList();
/// <summary>
/// Get the Item based on the ID
/// </summary>
/// <param name="name">ID of the Item to retrieve</param>
/// <returns>The Item with the given ID</returns>
public T GetItem(int id)
{
return (from item in ItemList
where (int)item.GetType().GetProperty("ID").GetValue(item, null) == id
select item).SingleOrDefault();
}
/// <summary>
/// Get the Item based on the Name
/// </summary>
/// <param name="name">Name of the Item to retrieve</param>
/// <returns>The Item with the given Name</returns>
public T GetItem(string name)
{
return (from item in ItemList
where (string)item.GetType().GetProperty("Name").GetValue(item, null) == name
select item).SingleOrDefault();
}
}
然后是我的缓存类,它基本上包含我的查询字典
public static class DALCache
{
static Dictionary<string, object> _AppCache = new Dictionary<string, object>();
public static T GetItem<T>(string key)
{
if(_AppCache.ContainsKey(key))
{
return (T) _AppCache[key];
}
else
{
return default(T);
}
}
public static void SetItem(string key, object obj)
{
_AppCache.Add(key, obj);
}
}
最后是一个带有缓存列表的实现。我使用 EF 获取我的 CustomerType 列表并将其缓存到应用程序生命的剩余时间。您可以根据需要更改此设置。
public class CustomerTypeDAL: DALBaseCache<CustomerType>
{
protected override List<CustomerType> GetItemList()
{
DBEntities entities = new DBEntities();
return Mapper.Map <List<CustomerType>>(entities.GetAllCustomerTypes().ToList());
}
}
在您的代码中的任何地方,您都可以将其用作:
CustomerTypeDAL customerTypeDAL = new CustomerTypeDAL();
List<CustomerType> custTypes = customerTypeDAL.ItemList;
第一次调用它时,它会从 DB 中获取它。之后,它将在缓存之后。