2012-03-16 64 views
1

我有一個few extensions methods我用我的asp.net web表單來管理網格視圖行格式。有沒有辦法注入/交換擴展?

基本上,他們作爲一種「服務」的,以我的代碼隱藏類:

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     var row = e.Row; 
     if (row.RowType == DataControlRowType.DataRow) 
     { 
      decimal amount = Decimal.Parse(row.GetCellText("Spend")); 
      string currency = row.GetCellText("Currency"); 
      row.SetCellText("Spend", amount.ToCurrency(currency)); 
      row.SetCellText("Rate", amount.ToCurrency(currency)); 
      row.ChangeCellText("Leads", c => c.ToNumber()); 
     } 
    } 

不像類的實例,他們沒有與一個DI容器中使用的接口。

有什麼方法可以獲得可交換擴展的功能嗎?

回答

3

不是在執行時,不是 - 畢竟,它們只是作爲靜態方法調用綁定。

如果你想能換出來,你可能要考慮他們,而不是接口...

如果你感到快樂換出來的編譯 - 時間,只要改變你的使用指示。

2

靜態類是一個橫切關注點。如果您將其實現提取到非靜態類中,您可以使用靜態類來執行DI。然後你可以把具體的實現分配給你的靜態類字段。

好了,我的C#是更好的,那麼我的英語...

//abstraction 
interface IStringExtensions 
{ 
    bool IsNullOrWhiteSpace(string input); 
    bool IsNullOrEmpty(string input); 
} 

//implementation 
class StringExtensionsImplementation : IStringExtensions 
{ 
    public bool IsNullOrWhiteSpace(string input) 
    { 
     return String.IsNullOrWhiteSpace(input); 
    } 

    public bool IsNullOrEmpty(string input) 
    { 
     return String.IsNullOrEmpty(input); 
    } 
} 

//extension class 
static class StringExtensions 
{ 
    //default implementation 
    private static IStringExtensions _implementation = new StringExtensionsImplementation(); 

    //implementation injectable! 
    public static void SetImplementation(IStringExtensions implementation) 
    { 
     if (implementation == null) throw new ArgumentNullException("implementation"); 

     _implementation = implementation; 
    } 

    //extension methods 
    public static bool IsNullOrWhiteSpace(this string input) 
    { 
     return _implementation.IsNullOrWhiteSpace(input); 
    } 

    public static bool IsNullOrEmpty(this string input) 
    { 
     return _implementation.IsNullOrEmpty(input); 
    } 
} 
+0

+1這小子讓我想起了所謂的[提供商模式]的(http://msdn.microsoft.com/en -us /庫/ ms972319.aspx) – 2012-03-18 00:38:27

相關問題