I\'ve made a class that is a cross between a singleton (fifth version) and a (dependency injectable) factory. Call this a \"Mono-Factory?\" It works, and looks like this:<
Note: This is a complete rewrite of the original answer; the recommendation still stands, however.
First: make sure you're not running under a debugger. For example, a watch window could touch your public static properties. This is one of the possible reasons the second example could behave differently from the first. It may sound silly, but you never know.
Under .NET 4, your second example does work, and I'd honestly expect it to work under .NET 2 as well. As long as you don't touch the Context.Log property or LogFactory.instance field inadvertently. Yet, it looks terribly fragile.
Also, strictly speaking, the beforefieldinit subtleties you're trying to use here can bite you in a multi-threaded application: the init of LogFactory does not need to run on the same thread as the setter of Context.Log[Object]. This means that when LogFactory.instance is initialized, on that thread Context.LogObject need not be set yet, while it is on another (such syncs can happen lazily). So it is not thread safe. You can try to fix this by making Context.LogObject volatile, that way the set is seen on all threads at once. But who knows what other race conditions we get into next.
And after all the tricks, you're still left with the following rather unintuitive result:
Context.Log = value1; // OK
Context.Log = value2; // IGNORED
You'd expect the second invocation of the setter to either work (Context.Log == value2) or to throw. Not to be silently ignored.
You could also go for
public static class Context
{
private static BaseLogger LogObject;
public static BaseLogger Log
{
get { return LogObject ?? LogFactory.instance; }
set { LogObject = value; }
}
private class LogFactory
{
static LogFactory() {}
internal static readonly BaseLogger instance
= new BaseLogger(null, null, null);
}
}
Here the result is guaranteed, and lazy (in line with Jon Skeet's fifth singleton method). And it looks a lot cleaner IMHO.