Share via


How to update values of singleton class instance?

Question

Friday, July 25, 2014 7:03 PM

Hi,

I have a class called RequestManager, it's a singleton class and has a method UpdateConfiguration(ConfigurationClass1 config) and another method StartSendRequest().

This class will be called in another class.

The actual call will be 

RequestManager.Instance.StartSendRequest();

Before calling this method, I need to update its configuration. The code for that will be RequestManager.UpdateConfiguration(newConfig).

My question is if I call RequestManager.UpdateConfiguration(newConfig), then call RequestManager.Instance.StartSendRequest(), will the instance generated pick up the change?

Thanks

Peney

All replies (3)

Friday, July 25, 2014 7:20 PM âś…Answered

If you're questioning whether the config change will be picked up or not then it would seem that you probably shouldn't be using a singleton at all.  If you were to create a new instance when you needed it and then configured it that would more closely line up with what you are wanting to do.  This is especially true if you'll be updating the configuration each time you call your request.  That is a clear indication you should be using a regular class and not a singleton.

Note that if you want to have some default behavior then you can define the default configuration (or whatever) in a separate type and then have all instances of your request manager initialize to the "default" configuration.  This gives you the same behavior as a singleton but still allows each instance to be updateable (if needed).

Michael Taylor
http://msmvps.com/blogs/p3net


Friday, July 25, 2014 7:11 PM

By Singleton, I assume that the constructor of the class always returns the same instance and perhaps keeps a reference count of times called.  As such, after you call RequestManager.UpdateConfiguration, all bits of code that have a reference to this class will reflect the change. 


Friday, July 25, 2014 11:56 PM

 Thanks for the reply. It's a class in a service library.