将事件作为依赖项注入

本文关键字:注入 依赖 事件 | 更新日期: 2023-09-27 17:53:56

我需要我的类来处理System.Windows.Forms.Application.Idle -然而,我想要删除特定的依赖,以便我可以对它进行单元测试。理想情况下,我想把它传递到构造函数中,比如:

var myObj = new MyClass(System.Windows.Forms.Application.Idle);

目前,它抱怨我只能使用+=和-=操作符的事件。有办法做到这一点吗?

将事件作为依赖项注入

你可以在接口后面抽象事件:

public interface IIdlingSource
{
    event EventHandler Idle;
}
public sealed class ApplicationIdlingSource : IIdlingSource
{
    public event EventHandler Idle
    {
        add { System.Windows.Forms.Application.Idle += value; }
        remove { System.Windows.Forms.Application.Idle -= value; }
    }
}
public class MyClass
{
    public MyClass(IIdlingSource idlingSource)
    {
        idlingSource.Idle += OnIdle;
    }
    private void OnIdle(object sender, EventArgs e)
    {
        ...
    }
}
// Usage
new MyClass(new ApplicationIdlingSource());
public class MyClass
{
    public MyClass(out System.EventHandler idleTrigger)
    {
        idleTrigger = WhenAppIsIdle;
    }
    public void WhenAppIsIdle(object sender, EventArgs e)
    {
        // Do something
    }
}
class Program
{
    static void Main(string[] args)
    {
        System.EventHandler idleEvent;
        MyClass obj = new MyClass(out idleEvent);
        System.Windows.Forms.Application.Idle += idleEvent;
    }
}