Lazy Property Initialization in static class C#

喜欢而已 提交于 2020-07-21 07:41:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!