如何重新在C#中单一实例实例、中单一

2023-09-04 13:11:35 作者:我找不到理由放棄

我有一个单例类,它是在读取配置文件。

 公共密封类SettingsHelper
    {
        私人静态只读SettingsHelper _instance =新SettingsHelper();

        静态SettingsHelper()
        {
        }

        公共静态SettingsHelper实例
        {
            得到
            {
                返回_instance;
            }
        }

        私人的NameValueCollection _SettingsSection = NULL;

        公共SettingsHelper()
        {
            _SettingsSection =新的NameValueCollection(ConfigurationManager.AppSettings);
        }

        .....
    }
}
 

但是,如果配置文件中得到改变的单不拿起变化。 有没有什么办法可以重新单身(调用它的构造函数)或我的实例应该创建一个将重新发起单实例单独的方法?

解决方案

您正试图扔掉Singleton模式的第一宗旨。单身是存在的,只是prevent实例化该类的一个新实例任何其他code。为了使单个类,你不应该在所有具有公共构造。你已经有一个公共的构造。

我鼓励你阅读的第一线,有关Singleton模式这个维基百科的文章

C 运算符 三

您正在尝试做的,被称为缓存依赖在C#中。你试图缓存Web.config文件的应用程序设置,你都依赖于Web.config中的变化。你应该寻找的。

I have a singleton class, it is reading config file.

public sealed class SettingsHelper
    {
        private static readonly SettingsHelper _Instance = new SettingsHelper();

        static SettingsHelper()
        {
        }

        public static SettingsHelper Instance
        {
            get
            {
                return _Instance;
            }
        }

        private NameValueCollection _SettingsSection = null;

        public SettingsHelper()
        {
            _SettingsSection = new NameValueCollection(ConfigurationManager.AppSettings);           
        }

        .....
    }
}

But if config file getting changed the singleton do not picking up the change. Is there any way to recreate the instance of singleton(call its constructor) or i should create separate method which will be reinitiating the instance of singleton?

解决方案

You're trying to throw away the very first purpose of singleton pattern. A singleton is there, just to prevent any other code from instantiating a new instance of that class. To make a singleton class, you should not have public constructors at all. You already have a public constructor.

I encourage you to read the first line, just the first line of this Wikipedia article about Singleton Pattern.

What you're trying to do, is called cache dependency in C#. You're trying to cache Web.config's app settings and you are dependent on Web.config's change. You should search that.