3

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

2
  • 1
    Because when you create _log, LoggerFactory is null. By the time you do Logger.LoggerFactory = ... you've already initialized _log Commented Jul 27, 2016 at 14:41
  • You could try: private static readonly Lazy<ILogger> _log = new Lazy<ILogger>(() => LoggerFactory()); Commented Jul 27, 2016 at 14:42

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

Thanks for the explanation, now I understand the exec order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.