注入事件作为依赖项

6

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

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

目前,它提示我只能使用+=和-=运算符与事件一起使用。有没有办法做到这一点?

2个回答

10

你可以通过一个接口来抽象化事件:

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());

3
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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接