2012-10-23 27 views
0

我爲我的MVC應用程序創建了一個自定義緩存提供程序。我將使用此類將會話數據存儲/檢索到外部服務(如memcached或Redis)。如何在MVC中全局訪問一個對象

我想在應用程序啓動時創建一次對象實例,以便我可以從任何控制器引用該對象,並且只需要將該實例「新建」一次。我在想,我會在Global.asax Application_Start方法中實例化這個類。但是,實例似乎無法在任何控制器中訪問。

在MVC中實例化並訪問(全局)類的首選方法是什麼?

這裏是我的「簡化」類的副本:

public class PersistentSession : IPersistentSession 
    { 
     // prepare Dependency Injection 
     public ICache cacheProvider { get; set; } 

     public bool SetSessionValue(string key, string value) 
     { 
      return cacheProvider.PutToCache(key, value); 
     } 

     public bool SetSessionValue(string key, string value, TimeSpan expirationTimeSpan) 
     { 
      return cacheProvider.PutToCache(key, value, expirationTimeSpan); 
     } 

     public string FetchSessionValue(string key) 
     { 
      return cacheProvider.FetchFromCache(key); 
     } 
    } 

我想將它實例化一個時間,這樣我可以從所有控制器應用程序訪問寬,這樣的事情:

// setup PersistentSession object 
persistentSession = new PersistentSession(); 
string memcachedAddress = WebConfigurationManager.AppSettings["MemcachedAddress"].ToString(); 
string memcachedPort = WebConfigurationManager.AppSettings["MemcachedPort"].ToString(); 

persistentSession.cacheProvider = new CacheProcessor.Memcached(memcachedAddress, memcachedPort); 

哪裏/如何在MVC中實例化對象以獲得來自所有控制器的全局訪問權限?

+0

你的意思是,除了[singleton](http://en.wikipedia.org/wiki/Singleton_pattern)? (在這種情況下,追求[DI](http://en.wikipedia.org/wiki/Dependency_injection)) –

+0

我只是堅持讓單身人士工作。我知道這應該是愚蠢的容易,但是作爲MVC的新手,我錯過了關於如何實例化單例的事情,以便我可以在控制器中「看」類。我試圖避免在每個控制器中新增我的類,並且不確定在MVC中的位置。 DI可以在此後不久... –

+0

這聽起來像你需要閱讀[「靜態」在C#中的意思](http://msdn.microsoft.com/en-us/library/79b3xss3(v = vs 0.80)的.aspx)。 –

回答

1

我看不到問題!

所有你需要做的是(靜態)關鍵字添加到PersistentSession類的方法的定義:

public class PersistentSession : IPersistentSession 
{ 
    // prepare Dependency Injection 
    public static ICache cacheProvider { get; set; } 

    public static bool SetSessionValue(string key, string value) 
    { 
     return cacheProvider.PutToCache(key, value); 
    } 

    public static bool SetSessionValue(string key, string value, TimeSpan expirationTimeSpan) 
    { 
     return cacheProvider.PutToCache(key, value, expirationTimeSpan); 
    } 

    public static string FetchSessionValue(string key) 
    { 
     return cacheProvider.FetchFromCache(key); 
    } 
} 

。您可以使用下面的代碼從任何地方訪問它們

PersistentSession.SetSessionValue (key , value); 

你也可以添加靜態構造函數訪問任何成員之前初始化所有領域,併爲被訪問靜態類的成員之前調用構造函數第一次,所以你可以確定你的課程在使用之前就已經設置好了。

public static PersistentSession() 
{ 
//Put your initializing code, for example: 
cacheProvider = new CacheProvider(); 
} 
+0

答案似乎只是將接口從靜態類中刪除。 –

相關問題