Introduce an event as a dependency

I need my class to handle System.Windows.Forms.Application.Idle - however I want to remove this specific dependency so that I can unit test it. Therefore, ideally, I want to pass it in the constructor - something like:

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

He is currently complaining that I can only use the event with the + = and - = operators. Is there any way to do this?

+5
source share
2 answers

You can abstract the event behind the interface:

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());
+9
source
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;
    }
}
+3
source

All Articles