C# 将事件作为依赖项注入

C# 将事件作为依赖项注入,c#,events,dependency-injection,C#,Events,Dependency Injection,我需要我的类来处理System.Windows.Forms.Application.Idle-但是,我想删除这个特定的依赖项,这样我就可以对它进行单元测试。因此,理想情况下,我希望在构造函数中传递它-类似于: var myObj = new MyClass(System.Windows.Forms.Application.Idle); 目前,它抱怨我只能使用带有+=和-=运算符的事件。有什么方法可以做到这一点吗?您可以在接口后面抽象事件: public class MyClass {

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

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

目前,它抱怨我只能使用带有+=和-=运算符的事件。有什么方法可以做到这一点吗?

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

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