2012-01-20 22 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