【问题标题】:C# How to resolve circular dependency caused by EditorAttribute usage?C#如何解决EditorAttribute使用引起的循环依赖?
【发布时间】:2011-06-01 10:33:33
【问题描述】:

在我的项目中,我有两个库目前会导致我无法解决的循环依赖。

一个库为整个解决方案提供通用数据结构。这个库包含一个类似这样的结构:

namespace Common {
  public class Foo {
    //[Editor( typeof( UserEditor ), typeof( UITypeEditor ) )]
    public UInt32 OwnerId { get; set; }
  }

  public class User {
    public UInt32 Id { get; set; }
  }
}

现在在我们解决方案中的一个项目中,我们想通过 PropertyGrid 编辑 Foo 实例,并且应该使用自定义编辑器编辑 OwnerId 属性;这个:

using Common;

namespace Common.Gui {
  public class OwnerEditor : UITypeEditor {
    public static List<User> Users { get; set; }
  }
}

现在,我不能只将EditorAttribute 添加到Foo.OwnerId,因为这会产生循环依赖,而且我想保留对Common.Gui 的引用而不是Common。我还想避免将代码从 Common 拉到新程序集中,因为许多其他项目都引用它。

我发现了一个关于 adding EditorAttribute at runtime 的问题,这听起来像是一个完美的解决方案,但我无法熟练地解决我的问题。

【问题讨论】:

    标签: c# circular-dependency


    【解决方案1】:

    我认为这是一个有缺陷的设计的标志。您是否希望包含 Foo 的类库不知道编辑 GUI?在这种情况下,它不应该包含 EditorAttribute。

    一种解决方案可能是将 Foo 类视为 MVVM 架构中的模型。然后您可以在应用EditorAttribute 的GUI 类库中创建一个包装ViewModel。如果您提取我放置在模型类库中的接口 IFoo,您可以使用装饰器模式。

    【讨论】:

      【解决方案2】:

      您可以通过名称引用编辑器类来创建运行时引用。

      public class Foo {
          [Editor( "Common.Gui.OwnerEditor, Common", typeof( UITypeEditor ) )]
          public UInt32 OwnerId { get; set; }
        }
      

      【讨论】:

      • 不过,我同意安德斯的回答。你的 Common 模块仍然知道你的 GUI 模块,所以它不是一个很好的设计。
      • +1:您可以在所有引用 *.Design.dll 的 MS 库中看到这一点。
      • 其实我一开始也尝试过解决依赖,但是导致PropertyGrid中无法使用编辑器。编辑:我的错误,这是由错字引起的。这个建议现在很好用。
      猜你喜欢
      • 2013-02-04
      • 2012-03-15
      • 2016-09-21
      • 2010-11-29
      • 2012-03-09
      • 2020-11-12
      相关资源
      最近更新 更多