Search code examples
c#asp.netstatic-classes

Using a Static Class to Initialize Members of another Static Class in ASP .NET


Is there anyway for a static class to use values set in another static class from a different namespace to initialize some of it's members? Is there anyway to dictate the order they get established in?

e.g.

namespace Utility
{
    using Config;

    public static class Utility
    {
        public static UtilityObject myUtil = new UtilityObject(ConfigContext.myValue)
    }
}
...
// somewhere in a different file/project
...
namespace Config
{
    public static class ConfigContext
    {
        public static string myValue => ConfigurationManager.AppSettings["key"];
    }
}

This is a simplified example of the basic pattern I'm trying to accomplish; I would like to take values that are in a config file which are loaded into static class ConfigContext , and use them to initialize members of a static class Utility .


Solution

  • You can't dictate the order of static initialization. But you can avoid the problem entirely by deferring initialization using lazy logic.

    public static class Utility
    {
        private static Lazy<UtilityObject> _myUtil = null;
    
        private static Utility()
        {
            _myUtil = new Lazy<UtilityObject>( () => new UtilityObject(ConfigContext.myValue) );
        }
    
        public static myUtil => _myUtil.Value;
    }
    

    Using this technique, the utility object isn't initialized until it is actually used.

    If the logic to initialize ConfigContext has a similar issue, you can use a Lazy there too, and all of your lazy fields will get initialized in a cascading fashion, in the order they are needed.