OK so im trying to create a settings class to store certain strings that i need to access throughout the system. I have created a globalSettings.cs with the code below:
public class GlobalSettings { private readonly Hashtable myHT; public GlobalSettings() { //Hashtable used to store global strings myHT = new Hashtable(); myHT.Add('logCategory','TMBC'); //event log category myHT.Add('logSource', 'MVC'); //event log source //setup required options //Create log source if required if (!EventLog.SourceExists(myHT['logSource'].ToString())) { EventLog.CreateEventSource(myHT['logSource'].ToString(), myHT['logCategory'].ToString()); } } public string getSetting(string key) { return myHT.ContainsKey(key) ? myHT[key].ToString() : null; } }
At the moment i have initialised this class in each one of my controllers with the following:
protected GlobalSettings globalSettings = new GlobalSettings();
**Should i set the constructor to private and implement the singleton pattern as it is afterall a settings class and only need one instance?
Would i be better off extending the controller class with the setting information in it?
**
Personally, I’d rather compartmentalize those things. For example, why do all your controllers need to know about writing event logs? I’d have a single LogWriter class and ILogWriter interface, and use dependency injection (see MVCContrib for samples) – i.e.
(and using a DI-based controller-factory)
This allows you to unit test the log-writing by mocking the log-writer. Then the settings would fit reasonably well as constants (or fetched from config) inside the LogWriter class.
Re the specific question; if all the values are constant, use constants (or maybe static properties):
A dictionary would be useful if they are fetched from configuration; if they are truly global, a static dictionary should suffice – instances would only be useful if it changes between impressions. A singleton would serve no purpose here; use static members instead.