我爲我的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中實例化對象以獲得來自所有控制器的全局訪問權限?
你的意思是,除了[singleton](http://en.wikipedia.org/wiki/Singleton_pattern)? (在這種情況下,追求[DI](http://en.wikipedia.org/wiki/Dependency_injection)) –
我只是堅持讓單身人士工作。我知道這應該是愚蠢的容易,但是作爲MVC的新手,我錯過了關於如何實例化單例的事情,以便我可以在控制器中「看」類。我試圖避免在每個控制器中新增我的類,並且不確定在MVC中的位置。 DI可以在此後不久... –
這聽起來像你需要閱讀[「靜態」在C#中的意思](http://msdn.microsoft.com/en-us/library/79b3xss3(v = vs 0.80)的.aspx)。 –