将事件注入为依赖项

Sma*_*ery 5 c# events dependency-injection

我需要我的类来处理System.Windows.Forms.Application.Idle - 但是,我想要删除那个特定的依赖项,以便我可以对它进行单元测试.理想情况下,我想在构造函数中传递它 - 类似于:

var myObj = new MyClass(System.Windows.Forms.Application.Idle);
Run Code Online (Sandbox Code Playgroud)

目前,它抱怨我只能使用带+ =和 - =运算符的事件.有没有办法做到这一点?

Bry*_*tts 9

您可以在界面后面抽象事件:

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());
Run Code Online (Sandbox Code Playgroud)