2012-03-16 40 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

相关问题