2012-01-20 21 views
0

我有一個函數,公共類中的函數很簡單。緩存MVC項目中的Hashtable

這個函數創建一個Hashtable對象與數據庫,他的功能是這樣的部分給定的信息:

try { 
      while (dataReader.Read()) { 
       Hashtable table1= new Hashtable(); 
       Hashtable table2= new Hashtable(); 

       table1.Add(dataReader["field1"].ToString(), Localization.English(dataReader["field1"]); 

       table2.Add(dataReader["field2"].ToString(), Localization.French(dataReader["field2"]); 
      } 
     } catch (Exception e) { 
      Console.WriteLine(e.Message); 
     } 

我想緩存這兩個Hashtable S和其他類中使用它們。據我所知,即使我使用System.Web命名空間,我也不能使用HttpRuntime.Cache

我看到HttpRuntime.Cache可以在Model類中使用。

是否有其他方法來緩存這些Hashtable s? PS:如果我的問題很差,對不起,對不起。

+0

你能在elabortate的價值,爲什麼你unsable使用HttpRuntime.Cache? –

+0

'我看到HttpRuntime.Cache可以用於-Model-class。' –

+0

附加說明;如果Web緩存不適合某種原因,也會有MemoryCache(或者名稱與此類似)。另外,'HashTable':注意所有更新都必須同步(儘管讀取操作不需要同步) –

回答

1

如果您有兩個項目,如模型或實體項目和Web項目,您只需在Models項目中添加一個引用到System.Web。如果您沒有添加對System.Web的引用,那麼即使System.Web有一個名稱空間,您也無法訪問HttpRuntime或HttpContect。

後你這樣做,你將有機會獲得:

System.Web.HttpRuntime.Cache 

,並可以使用

HttpRuntime.Cache.Insert(
            CacheKey, 
            CacheValue, 
            null, 
            DateTime.Now.AddMinutes(CacheDuration), 
            Cache.NoSlidingExpiration 
           ); 

Hashtable table1 = HttpRuntime.Cache[CacheKey] as Hashtable; 
HttpRuntime.Cache.Remove(CacheKey); 

您也將有機會獲得

System.Web.HttpContext.Current.Application 

,並可以使用

System.Web.HttpContext.Current.Application.Add("table1",myHashTable); 
Hashtable table1 = System.Web.HttpContext.Current.Application["table1"] as Hashtable; 
1

您可以使用靜態類。

 public static class MyDictionary 
    { 
     public static Dictionary<string,string> French = new Dictionary<string,string>(); 

     public static Dictionary<string,string> English=new Dictionary<string,string>(); 
      public static MyDictionary(){ 
      while (dataReader.Read()) { 
      MyDictionary.English.Add(dataReader["field1"].ToString(),Localization.English(dataReader["field1"])); 
      MyDictionary.French.Add(dataReader["field2"].ToString(),Localization.French(dataReader["field2"])); 
      } 
     }   
     } 

然後,如果你想獲得一個字

MyDictionary.English["Car"]; // this'll return a string value. if contains 
MyDictionary.French["Car"]; // this'll return a string value. if contains 
+0

如果使用靜態類,則不需要將讀取器放在Global.asax /的Application_Start。你只需要爲MyDictionary創建一個靜態構造函數並在其中加載值。這樣,您的應用程序將不需要在首次訪問數據之前加載數據。請記住,在Application_Start中放置的任何東西都必須在應用程序池循環之前運行。您投入的時間越長,應用的開始時間就越長。 –

+0

嗨Splash-X。你是對的。我沒有想到構造函數。結構比Application_Start更好,謝謝。 – halit