有没有办法注入/交换扩展?

时间:2012-03-16 23:33:01

标签: c# asp.net dependency-injection extension-methods mixins

我在我的asp.net网络表单中使用few extensions methods来管理网格视图行格式。

基本上,它们作为我的代码背后的代码的一种“服务”:

    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容器一起使用的接口。

有没有办法获得可交换扩展的功能?

2 个答案:

答案 0 :(得分:3)

不是在执行时,不是 - 毕竟,它们只是作为静态方法调用绑定。

如果希望能够将它们交换出来,您可能需要考虑放在接口中而不是......

如果您很乐意在编译时间将它们换掉,只需更改您的使用指令。

答案 1 :(得分: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);
    }
}
相关问题