Singleton Class (ConfigurationManager):?
- The ConfigurationManager class is designed to ensure that there is only one
instance of it throughout the application.
- The Instance property handles the lazy initialization of the singleton instance,
ensuring that it's only created once and then reused.
public class ConfigurationManager
private static ConfigurationManager _instance;
private static readonly object _lock = new object(); // Lock
for thread safety
private ConfigurationManager() { } // Private constructor to
prevent instantiation
public static ConfigurationManager Instance
get
lock (_lock) // Ensure thread safety
return _instance ??= new ConfigurationManager(); //
Lazy initialization
Follow:
public string GetSetting(string key) => "some value"; // Example
method to return a setting
- Private Constructor:
- The constructor is private, preventing external code from creating instances
directly. This ensures that the class cannot be instantiated more than once.
- Static Instance Property:
- The Instance property is used to access the unique instance of
ConfigurationManager. It uses lazy initialization to create the instance
only when it's first needed.
- Thread Safety:
- The lock (_lock) statement ensures that the instance creation is
thread-safe, preventing multiple threads from creating multiple instances at
the same time in a multithreaded environment.
- Lazy Initialization (??=):
- The ??= operator ensures that the instance is only created if it's null,
ensuring that the instance is created only once and reused thereafter.