2011-09-18 174 views
7

我需要从某些参考数据中填充一些下拉框。即城市名单,国家列表等。我需要填写各种网络表格。我认为,我们应该将这些数据缓存在我们的应用程序中,这样我们就不会在每个表单上都打上数据库。我对缓存和ASP.Net很陌生。请告诉我如何做到这一点。ASP.Net中的数据缓存

回答

13

我总是将以下类添加到我的所有项目中,使我可以轻松访问Cache对象。实现这一点,继哈桑汗的答案将是一个很好的方法。

public static class CacheHelper 
    { 
     /// <summary> 
     /// Insert value into the cache using 
     /// appropriate name/value pairs 
     /// </summary> 
     /// <typeparam name="T">Type of cached item</typeparam> 
     /// <param name="o">Item to be cached</param> 
     /// <param name="key">Name of item</param> 
     public static void Add<T>(T o, string key, double Timeout) 
     { 
      HttpContext.Current.Cache.Insert(
       key, 
       o, 
       null, 
       DateTime.Now.AddMinutes(Timeout), 
       System.Web.Caching.Cache.NoSlidingExpiration); 
     } 

     /// <summary> 
     /// Remove item from cache 
     /// </summary> 
     /// <param name="key">Name of cached item</param> 
     public static void Clear(string key) 
     { 
      HttpContext.Current.Cache.Remove(key); 
     } 

     /// <summary> 
     /// Check for item in cache 
     /// </summary> 
     /// <param name="key">Name of cached item</param> 
     /// <returns></returns> 
     public static bool Exists(string key) 
     { 
      return HttpContext.Current.Cache[key] != null; 
     } 

     /// <summary> 
     /// Retrieve cached item 
     /// </summary> 
     /// <typeparam name="T">Type of cached item</typeparam> 
     /// <param name="key">Name of cached item</param> 
     /// <param name="value">Cached value. Default(T) if item doesn't exist.</param> 
     /// <returns>Cached item as type</returns> 
     public static bool Get<T>(string key, out T value) 
     { 
      try 
      { 
       if (!Exists(key)) 
       { 
        value = default(T); 
        return false; 
       } 

       value = (T)HttpContext.Current.Cache[key]; 
      } 
      catch 
      { 
       value = default(T); 
       return false; 
      } 

      return true; 
     } 
    } 
+0

不错的代码... upvoted –

2

从你的其他问题我读到,你正在使用3层架构与达尔,业务和表示层。

所以我假设你有一些数据访问类。理想的做法是获得相同类的缓存实现,然后进行缓存。例如:如果你有一个IUserRepository接口,那么UserRepository类将实现它并通过方法在db中添加/删除/更新条目,然后你也可以拥有CachedUserRepository,它将包含UserRepository对象的实例以及它将首先看到的get方法进入缓存,对照某个键(从方法参数派生),如果找到该项,则返回它,否则调用内部对象上的方法;获取数据;添加到缓存然后返回。

您的CachedUserRepository显然也会有缓存对象的实例。有关如何使用Cache对象的详细信息,请参阅http://msdn.microsoft.com/en-us/library/18c1wd61(v=vs.85).aspx

+1

......只是针对一般文化/词汇,这叫做“装饰者”模式。也就是说,你用一个额外的实现缓存的功能“装饰”了初始仓库。 – tsimbalar