2013-03-06 49 views
3

我使用給定的單例模式來緩存ASP.NET中的類對象。任何人都可以強調這種方法的缺點嗎?Disadvanage給定Singleton緩存模式

public class CacheManager 
{ 
private static CacheManager _instance; 

protected CacheManager(string key) { id = key; } 
public static CacheManager getInstance(string key) 
{ 
    if (HttpContext.Current.Cache[key] == null) 
     HttpContext.Current.Cache.Insert(key, _instance = new CacheManger(key), null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(120),CacheItemPriority.Default,new CacheItemRemovedCallback(ReportRemovedCallback)); 

    return (CacheManager)HttpContext.Current.Cache[key]; 
} 

private static void ReportRemovedCallback(string CacheManager, object value, CacheItemRemovedReason reason) 
{    
    _instance = null; 
} 

public string id { get; private set; }   
public string field1 { get; set; } 
public string field2 { get; set; } 
public string field3 { get; set; }   
} 
+2

我不知道我是否會稱這是一個單身人士,本身。它只是靜態數據的靜態包裝。這基本上是'HttpContext.Current'所做的,你只需要添加特定於你的應用程序的helper。我沒有看到任何問題。 – Yuck 2013-03-06 13:33:41

+0

它不是線程安全的,但在此之前 - 你想在getInstance和ReportRemovedCallback方法中做什麼? – YavgenyP 2013-03-06 13:38:43

回答

2

我看不出有什麼理由讓你做這個單身人士。我只需爲每個獲取/設置值的屬性編寫一個包裝器。這樣你就可以用IoC容器更容易地注入它並提高可測性。

就目前而言,您的代碼並不是線程安全的,這也可能導致問題。

+0

雖然多於一個線程使用相同的'HttpContext.Current'實例工作? – Yuck 2013-03-06 13:37:28

+0

我不關心當前的上下文 - 這是線程本地。它的這個類。 '_instance'沒有被保護。 – 2013-03-06 13:38:12

+0

@Yuck,你爲什麼認爲它不太可能會有多個線程訪問'Cache'對象?它由應用程序域共享,不是嗎? – YavgenyP 2013-03-06 13:41:54