2012-06-19 25 views
5

我剛剛參與了一個經典的ASP.NET項目,其中包含大量來自會話和查詢字符串的存儲和讀取值。這可能看起來像下面這樣:遵循ASP.NET中的DRY原理

Session["someKey"]=someValue; 

而在代碼中的其他位置讀取會話中的值。很明顯,這違反了DRY原則,因爲您將字面字符串鍵遍佈整個代碼。避免這種情況的一種方法是將所有密鑰存儲爲常量,並在需要讀取和寫入會話的任何地方引用它們。但我不確定這是做到這一點的最佳方式。你會如何建議我最好處​​理這個問題,以免違反DRY原則?

回答

7

創建一個單獨的公共類,你可以定義常量,如

public class SessionVars 
{ 
    public const string SOME_KEY = "someKey"; 
    public const string SOME_OTHER_KEY = "someOtherKey"; 
} 

,然後在你的代碼的任何地方,你可以像這樣訪問會話變量:

Session[SessionVars.SOME_KEY]=someValue; 

這樣你就可以得到IntelliSence和其他花裏胡哨的。

+0

+1這是我傾向於遵循的模式 - 它確實有助於消除這些討厭錯字錯誤。 –

+1

你不應該在這種情況下使用'const'。 「靜態只讀」更合適(和安全)。 – EkoostikMartin

+1

這是如何緩解不重複自己的原則?你仍然在編寫同一個班輪,你只是使用一個常量變量而不是實例字符串作爲鍵? – BlackSpy

2

我認爲你的閱讀過於乾燥。我更多地關注可能包含在函數中的東西。即而不是在所有地方重複相同的五行,將這五行包裝在一個函數中,並在需要的地方調用函數。

作爲示例,您只需在字典(本例中爲會話對象)中設置一個值,這是在其中存儲和檢索對象的最簡單方法。

+1

我希望你永遠不會繼承一個項目充滿魔力*絃樂器*您必須保持... –

0

可選,你可以在鹼頁面訪問這個會話對象和屬性把它包:

class BasePage : Page 
{ 
    ... 
    public string MySessionObject 
    { 
     get 
     { 
     if(Session["myKey"] == null) 
      return string.Empty; 
     return Session["myKey"].ToString(); 
     } 
     set 
     { 
      Session["myKey"] = value; 
     } 
    } 
    ... 
} 

在這裏,你都在重複着myKey字符串,但它被封裝到屬性。如果你想要避免這種情況的極端,用鍵創建一個常量並替換字符串。

1

我不記得我的一生中,我虛心重新定意從這個代碼,但它是相當不錯的:

using System; 
using System.Web; 

namespace Project.Web.UI.Domain 
{ 
    public abstract class SessionBase<T> where T : class, new() 
    { 
     private static readonly Object _padlock = new Object(); 

     private static string Key 
     { 
      get { return typeof(SessionBase<T>).FullName; } 
     } 

     public static T Current 
     { 
      get 
      { 
       var instance = HttpContext.Current.Session[Key] as T; 

       lock (SessionBase<T>._padlock) 
       { 
        if (instance == null) 
        { 
         HttpContext.Current.Session[Key] 
          = instance 
          = new T(); 
        } 
       } 
       return instance; 
      } 
     } 

     public static void Clear() 
     { 
      var instance = HttpContext.Current.Session[Key] as T; 
      if (instance != null) 
      { 
       lock (SessionBase<T>._padlock) 
       { 
        HttpContext.Current.Session[Key] = null; 
       } 
      } 
     } 
    } 
} 

它背後的理念二折。創建的類型應該是您需要的唯一類型。它基本上是一個大的強類型包裝。所以,你有一些對象,你要保持在擴展信息:

public class MyClass 
{ 
    public MyClass() 

    public string Blah1 { get; set; } 
} 

然後在路上,你延伸MyClass,你不想記住所有的核心價值觀,將它們存儲在的AppSettings或常變量靜態類。您只需定義要存儲什麼:

public class MyClassSession : SessionBase<MyClass> 
{ 
} 

,隨時隨地在你的程序,你只需使用類。

// Any Asp.Net method (webforms or mvc) 
public void SetValueMethod() 
{ 
    MyClassSesssion.Current.Blah1 = "asdf"; 
} 

public string GetValueMethod() 
{ 
    return MyClassSession.Current.Blah1; 
}