This is my example of
logger wrapper from
Steven van Deursen.
The part available in the Stack Overflow article will not be repeated here; instead, I will focus on the WinForms-specific implementation.
Since I often build different tools using Windows Forms, I aim to have a central place to display information or errors in a TextBox that is immediately visible. The problem is that I want to have
constructor injection in Program.cs, which happens before any components in a form are created. To solve this, I added a TextBox property to my TextBoxLogger class:
namespace LoggerWrapper.Logger;
public class TextBoxLogger : ILogger
{
public TextBox? TextBox { get; set; }
public void Log(LogEntry entry)
{
TextBox?.AppendText(
$@"[{entry.Severity}] {DateTime.Now} {entry.Message} {entry.Exception}");
TextBox?.AppendText(Environment.NewLine);
}
}
Notice:
public TextBox? TextBox { get; set; }
Later, I will connect this property to the actual TextBox in Form1. Here’s what my Program.cs looks like:
using LoggerWrapper.Logger;
namespace LoggerWrapper
{
internal static class Program
{
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
var textBoxLogger = new TextBoxLogger();
var someDiClassHandler = new SomeDiClassHandler(textBoxLogger);
Form1 form1 = new Form1(someDiClassHandler);
textBoxLogger.TextBox = form1.TbLogger;
Application.Run(form1);
}
}
}
Notice:
textBoxLogger.TextBox = form1.TbLogger;
In Form1, I introduced a property named TbLogger:
namespace LoggerWrapper;
public partial class Form1 : Form
{
public TextBox? TbLogger { get; }
private readonly SomeDiClassHandler _someDiClassHandler;
public Form1(SomeDiClassHandler someDiClassHandler)
{
InitializeComponent();
TbLogger = tbLogger;
_someDiClassHandler = someDiClassHandler;
}
private void btnStart_Click(object sender, EventArgs e)
{
SomeDiClassCommand someDiClassCommand = new SomeDiClassCommand();
_someDiClassHandler.Execute(someDiClassCommand);
}
}
After creating Form1 I will assign TextBox to my TextBoxLogger, and in Form1 constructor I will assign TbLogger to real TextBox, in my case tbLogger:
TbLogger = tbLogger;
Example download from
here