2

它涉及以下内容:我有两个项目应该或多或少地彼此独立存在。项目一是一种文件系统观察器。另一个是我的 UI。如果有新文件,文件观察程序会引发事件。之后,应将文件中的数据添加到数据库中。这大致是背景故事。实际的问题是,文件观察者引发事件后,我想通知 UI 更新数据的视图。这意味着,事件应该由文件观察程序引发,并且应该在 UI 的实现中注册事件。现在的主要问题是我需要来自两个项目的类的实例。显然这会导致循环依赖问题。CP问题当然有接口的解决方案,但这并不能解决问题,我需要相同的对象来创建数据和事件注册。希望你能帮助我解决这个问题。谢谢。

4

2 回答 2

1

为什么您认为业务逻辑程序集中需要一个 UI 实例?

要注册事件处理程序,您通常只需要来自调用程序集的实例(观察者,已包含在调用程序集中)和引用程序集的实例(您的程序集包含文件系统观察程序)。

然后你有例如以下结构:

用逻辑组装

public class MyCustomWatcher
{   
    public event EventHandler Event;

    private void RaiseEventForWhateverReason()
    {
        if (Event != null)
        {
            Event(this, new Args());
        }
    }
   public Data GetData()
   {
    //return the data
   }
}

带有 UI 的程序集: - 表单和控制器类型都在此处声明。

class Form : System.Windows.Forms.Form
{
 public void DisplayNotification(Data data)
 {
   //actual code here
 }
}

class Controller 
{
    private Form form;
    private MyCustomWatcher watcher;

    public void Init()
    {
      this.watcher = CreateWatcher();
      RegisterEvents();
      ShowForm();
    }
    void ShowForm()
    {
     //show
    }
    void RegisterEvents()
    {
        this.watcher.Event += HandleChange;
    }

    void HandleChange(object sender /*this will be the instance that raised the event*/, SomeEventArgs e)
    {
        //BTW: this.watcher == sender; //the same instance

        form.DisplayNotification(this.watcher.GetData());
    }
}

带有 UI 的程序集引用带有逻辑的程序集。这里没有循环依赖。

于 2010-07-29T09:20:35.243 回答
0

我不确定我是否理解为什么 FileWatcher 会对你的 UI 有任何依赖,但既然你说它确实如此,你可以添加第三个项目作为两者之间的事件聚合器。这将使两个项目都依赖于聚合器,但会删除彼此的依赖关系。

于 2010-07-29T09:01:42.843 回答