Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject an event as a dependency

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

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

Currently, it's complaining that I can only use the event with += and -= operators. Is there a way to do this?

like image 800
Smashery Avatar asked Apr 29 '11 00:04

Smashery


People also ask

What are the three types of dependency injection?

There are three main styles of dependency injection, according to Fowler: Constructor Injection (also known as Type 3), Setter Injection (also known as Type 2), and Interface Injection (also known as Type 1).

What Does dependency injection mean?

In software engineering, dependency injection is a design pattern in which an object or function receives other objects or functions that it depends on. A form of inversion of control, dependency injection aims to separate the concerns of constructing objects and using them, leading to loosely coupled programs.

What is dependency injection with example?

Dependency injection (DI) is a technique widely used in programming and well suited to Android development. By following the principles of DI, you lay the groundwork for good app architecture. Implementing dependency injection provides you with the following advantages: Reusability of code.


2 Answers

You can abstract the event behind an 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());
like image 166
Bryan Watts Avatar answered Sep 30 '22 23:09

Bryan Watts


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;
    }
}
like image 30
Shrage Smilowitz Avatar answered Sep 30 '22 23:09

Shrage Smilowitz