ab_732
ab_732

Reputation: 3897

Lazy Property Initialization in static class C#

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

Upvotes: 3

Views: 15589

Answers (2)

Matt Burland
Matt Burland

Reputation: 45135

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.

Upvotes: 9

Steve
Steve

Reputation: 11963

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

Upvotes: 3

Related Questions