将事件注入为依赖项

时间:2011-04-29 00:09:19

标签: c# events dependency-injection

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

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

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

2 个答案:

答案 0 :(得分: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());

答案 1 :(得分: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;
    }
}