I often use delegates (e.g. Func<> or Action<>) to make code testable that would otherwise be using static methods. In this case, Trace.WriteLine:
public class TraceLogger : ILogger
{
private readonly TraceSwitch _traceSwitch;
private readonly string _category;
private readonly Action<string, string> _write;
public TraceLogger(TraceSwitch traceSwitch, string category, Action<string, string> write)
{
_traceSwitch = traceSwitch;
_category = category;
_write = write;
}
public void Debug(string message)
{
if (_traceSwitch.TraceVerbose)
_write(message, _category);
}
public void Info(string message)
{
if (_traceSwitch.TraceInfo)
_write(message, _category);
}
etc...
}
Every time the write action is called, the second argument is the same. So we can save ourselves some duplication by using partial function application (not currying, apparently!):
public class TraceLogger : ILogger
{
private readonly TraceSwitch _traceSwitch;
private readonly Action<string> _write;
public TraceLogger(TraceSwitch traceSwitch, string category, Action<string, string> write)
{
_traceSwitch = traceSwitch;
_write = m => write(m, category);
}
public void Debug(string message)
{
if (_traceSwitch.TraceVerbose)
_write(message);
}
public void Info(string message)
{
if (_traceSwitch.TraceInfo)
_write(message);
}
etc...
}