是否有注入/交换扩展的方法

本文关键字:扩展 方法 交换 注入 是否 | 更新日期: 2023-09-27 18:28:00

我在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容器的接口。

有什么方法可以获得可交换扩展的功能吗?

是否有注入/交换扩展的方法

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

如果希望能够交换它们,您可能需要考虑放在接口中。。。

如果您很乐意在编译时交换它们,只需更改using指令即可。

静态类是一个跨领域的问题。如果将静态类的实现提取到非静态类中,则可以使用静态类执行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);
    }
}