【问题标题】:Is there a way to inject/swap extensions?有没有办法注入/交换扩展?
【发布时间】:2012-04-02 12:01:35
【问题描述】:

我有一个 few extensions methods 我用我的 asp.net 网络表单来管理网格视图行格式。

基本上,它们对我的类后面的代码充当一种“服务”:

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    如果您愿意在编译时将它们换掉,只需更改您的 using 指令即可。

    【讨论】:

      【解决方案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);
          }
      }
      

      【讨论】:

      猜你喜欢
      • 2021-03-27
      • 2013-06-22
      • 2021-08-25
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多