static interfaces in c#
Sorry it's possibly a duplic开发者_如何转开发ate but in the other static interface they mention generics which I am not using.
I wanted a quick and simple logger for my app I though I could avoid a singleton using a static element. I would have like to keep the interface so that later I could change to another logging package. The interface being for me (I may be wrong here) a way to implement a "facade" feature.
I have the feeling I am overlooking something. A gentle push in the right direction would be greatly appreciated. (Hope it's a bit clearer)
public interface Ilogger
{
void Log(string data, out DateTime datetime, out string uid);
}
public class Logger : Ilogger
{
private static TraceSource AppTrace = new TraceSource("RD", SourceLevels.All);
static Logger ()
{
AppTrace.Listeners.Clear();
AppTrace.Listeners.Add(new DelimitedListTraceListener("RD.log"));
}
static void Log(string data, out DateTime datetime, out string uid)
{
datetime = DateTime.Now;
uid = Guid.NewGuid().ToString();
AppTrace.TraceInformation(datetime + ";" + uid + ";" + data);
}
}
You want to combine a singleton with a facade. Sort of a service locator. i.e. create a singleton that got the same methods as your interface and then assign the interface to the facade as the singleton.
I've blogged about it.
C# does not support static inheritance or static interface implementation. static variables are just a form of a Singleton either way you look at it - just go with a Singleton or better use a DI container to inject the logger dependency.
精彩评论