Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recreate singleton instance in c#

Tags:

c#

.net

singleton

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?

like image 653
sreginogemoh Avatar asked Oct 21 '25 16:10

sreginogemoh


1 Answers

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.

like image 200
Saeed Neamati Avatar answered Oct 23 '25 07:10

Saeed Neamati