2012-03-07 5 views
0

私はここ数ヶ月からC#.net MVC3プロジェクトの作業を開始しました。ネットの仕組みを理解するためのチュートリアルは行っていませんでしたが、Javaと.Netの比較に基づいて学習していました。今私は基本的なことを理解できませんでした。MVC3でアプリケーション固有のオブジェクトを使用するには?

私はアプリケーションレベルのキャッシュ(セッションレベルまたはリクエストレベルではない)を維持したいので、メモリディクショナリオブジェクトで作成し、それを再生したいと考えています。残念ながら、キャッシュオブジェクトは、global.asax.csファイルで宣言して初期化しても、私が推測するリクエストごとに再初期化されます。

ここに私のコードは私を助けてください。

CachedComponents.cs 
============== 

public class CachedComponents 
    { 
    private static readonly ILog log = LogManager.GetLogger("CachedComponents"); 
    private Dictionary<string, TridionComponent> componentCache = new Dictionary<string, TridionComponent>(); 

    public CachedTridionComponentsRepository() 
    { 
    } 
public bool IsExistInCache(string uri) 
    { 
     return componentCache.ContainsKey(uri); 
    } 

    public TridionComponent getCachedItem(string key) 
    { 
     if (componentCache.ContainsKey(key)) 
     { 
      log.Info("[getCachedItem] Cached Item found " + key); 
      return componentCache[key]; 
     } 
     else 
     { 
      return null; 
     } 

    } 

    public void Add(string key, TridionComponent value) 
    { 
     if (componentCache.ContainsKey(key)) 
     { 
      log.Debug("[Add] Item is already Cached...Cache has been Updated..."); 
      componentCache[key] = value; 
     } 
     else 
     { 
      log.Debug("[Add] Item has been added to cache"); 
      componentCache.Add(key, value); 
     } 
    } 

    } 

Global.asax.cs 
========= 
protected void Application_Start(object sender, EventArgs e) 
    { 
     AreaRegistration.RegisterAllAreas(); 
     RegisterGlobalFilters(GlobalFilters.Filters); 
     RegisterRoutes(RouteTable.Routes); 
     log4net.Config.XmlConfigurator.Configure(); 


     CachedComponents componentsCache = new CachedComponents(); 
     Application.Add("seeta", "seeta"); 
     Application.Add("componentsCache", componentsCache); 
    } 

    MyBusiness.cs 
    ============= 

    public class MyBusiness 
{ 
    private CachedComponets cache = null; 
    public MyBusiness() 
    { 
     if(cache == null) 
      cache = HttpContext.Cuurent.Application.get("componentsCache"); 
    } 
    public TridionComponent myBusinessMethod() 
    { 
     if (cache.IsExistInCach("uri")) 
      return cache.getCachedItem("uri"); 
     TridionComponent tc = GetTridionComponent(); 
     cache.Add("uri",tc); 
     return tc; 
    } 

} 

答えて

1

ILogで行ったように辞書をstaticに設定します。それは動作するはずです

+0

staticはクラス変数stuffのために意味されています...静的はどのようにこれに関連していますか...どのように悪い試みますが、何の希望もありません... –

+0

look here http://stackoverflow.com/a/313352/394028。たぶんそれは助けることができます(読み取り専用部分を無視してください) – Iridio

+0

あなたの答えをありがとう。それは静的なものに関するものではありませんが、あなたの答えは私に宣言をクラスにプッシュするように促しました(関数ではありません)。最初に、関数内でのオブジェクトの宣言と作成を行います。しかし、今はメンバー変数としてオブジェクトを作成しましたが、現在は機能しています。 CachedComponents宣言がApplication.Start()関数ではなく、Global.asax.csファイル内にある必要があることを意味します。 オブジェクトのスコープに問題がある可能性があります。私は本当に理解していますが、今はうまくいきます。 よろしく、 Seeta。 –

関連する問題