Constructor Injection with Action<bool> delegate in C#

524 Views Asked by At

Problem is that I need to inject dependency(Constructor dependency) between some handle class and some console application. Console application have state isRunning, which is obviously, bool variable. I could call exit command from console application, and then there is the problem. Since bool is value type, when we pass it as constructor parameter to some class, and then change it's value in that class, state of console application doesn't change. So I need to inject dependency. I have code like this.

private static class Program
{
    private static bool isRunning = true;

    private static void Main(string[] args)
    {
        ...
        var exitHandler = new ExitHandler(isRunning);
        do
        {
            exitHandler.Exit();
        }
        while (isRunning);
    }
}
... 
public class ExitHandler
{
   ...
   private readonly Action<bool> applicationState;
   ...
   public void Exit();

}

I know we can wrap bool value into class and than pass it as parameter, but somehow it can be done with Action delegate. The question is HOW?

2

There are 2 best solutions below

1
David Browne - Microsoft On BEST ANSWER

An Action can "capture" a local variable or field. So this is as simple as:

internal class Program
{
    static bool isRunning = true;
    static void Main(string[] args)
    {
        var exitHandler = new ExitHandler(() => isRunning = false) ;
        do
        {
            exitHandler.Exit();
        }
        while (isRunning);
    }
}
public class ExitHandler
{
    Action onExit;
    public ExitHandler(Action onExit)
    {
        this.onExit = onExit;
    }
   public void Exit() => onExit();

}
0
Enigmativity On

It seems to me that you could just use a CancellationTokenSource

internal class Program
{
    static void Main(string[] args)
    {
        var exitHandler = new CancellationTokenSource();
        do
        {
            exitHandler.Cancel();
        }
        while (!exitHandler.IsCancellationRequested);
    }
}

It's simpler and, as a bonus, thread-safe.