简体   繁体   中英

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?

eg

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM