问题
I have been given this code
public static class Logger
{
public static Func<ILogger> LoggerFactory;
private static readonly Lazy<ILogger> _log = new Lazy<ILogger>(LoggerFactory);
public static ILogger Instance
{
get
{
return _log.Value;
}
public static ILogger ConfigureLogging(string AppName, Version AppVersion)
{
// stuff
}
}
}
This static class is used in the application:
Logger.LoggerFactory = () => Logger.ConfigureLogging(AppName, AppVersion);
Logger.Instance.Information("Starting application");
I would expect the first row to set the LoggerFactory; however on the first attempt of writing to the log, an exception has thrown because the static Func LoggerFactory hasn't been set yet.
What's wrong with this code?
Thanks
回答1:
The quick and dirty fix for this would be to do this:
private static readonly Lazy<ILogger> _log = new Lazy<ILogger>(() => LoggerFactory());
Lazy
takes a function that will be executed when you first try to access the Value
, but in your code you are passing it null
because you haven't yet initialized LoggerFactory
. The static initializer in your class will run before the first time any of the static fields are accessed, so your attempt to access LoggerFactory
will trigger your _log
field to initialize (if it hasn't already) at which point LoggerFactory
is null. See, for example, here for some discussion on static initialization.
You can defer accessing LoggerFactory
but wrapping it in a function.
回答2:
Here is the execution order:
private static readonly Lazy<ILogger> _log = new Lazy<ILogger>(null);
//LoggerFactory is null at this point
Logger.LoggerFactory = () => Logger.ConfigureLogging(AppName, AppVersion);
Logger.Instance.Information("Starting application");
and thus _log will stay as null
来源:https://stackoverflow.com/questions/38616121/lazy-property-initialization-in-static-class-c-sharp