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?
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).
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.
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.
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());
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With