2012-01-20 3 views
0

나는 공용 클래스의 간단한 함수를 가지고있다.MVC 프로젝트에서 Hashtable 캐시하기

기능이 같은 자신의 기능의 일부, 데이터베이스에서 주어진 정보가 포함 된 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); 
     } 

합니다. 내가 아는 한 System.Web 네임 스페이스를 사용해도 HttpRuntime.Cache을 사용할 수 없습니다.

나는 HttpRuntime.CacheModel 클래스에서 사용될 수 있음을 알았다.

Hashtable을 다른 방법으로 캐시 할 수 있습니까?

추신 : 내 질문이 형편 없으면 죄송합니다.

+0

당신이에 elabortate 수있는 단어의 가치를 얻을 경우

 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"])); } } } 

는 그런 다음 HttpRuntime.Cache를 사용하는 unsable 왜? –

+0

'HttpRuntime.Cache가 -Model 클래스에서 사용될 수 있음을 알았습니다. ' –

+0

추가 노트; 웹 캐시가 어떤 이유로 적합하지 않은 경우 MemoryCache (또는 이와 유사한 이름)도 있습니다. 또한, 'HashTable' : 모든 업데이트가 동기화되어야 함을 유의하십시오 (읽기는 ** 동기화되지 않아도됩니다 **) –

답변

1

모델 프로젝트 또는 엔터티 프로젝트와 웹 프로젝트와 같이 두 프로젝트가 있다면 모델 프로젝트에 System.Web에 대한 참조를 추가하면됩니다. System.Web에 대한 참조를 추가하지 않은 경우 System.Web의 네임 스페이스가 있더라도 HttpRuntime 또는 HttpContect에 액세스 할 수 없습니다. 이렇게 한 후에

, 당신은에 액세스해야합니다 :

System.Web.HttpRuntime.Cache 

을하고 또한

System.Web.HttpContext.Current.Application 

에 액세스 할 수 있습니다 및 사용할 수

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.Add("table1",myHashTable); 
Hashtable table1 = System.Web.HttpContext.Current.Application["table1"] as Hashtable; 
1

정적 클래스를 사용할 수 있습니다. 당신 싶어

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

Hi Splash-X. 당신 말이 맞아요. 나는 생성자를 생각하지 않았다. Constructur는 Application_Start 덕분에 더 좋습니다. – halit