I have spent last couple of days reading about and trying different methods for creating and using a singleton instance of one of my class files and then using the reference as I need throughout the life of the program here on stackoverflow and well as a few other sites, and have found that there are soooo many opinions, suggestions and examples that work that I have gotten a little confused, especially when it comes to actually using the singleton object.
I have something that functions but I do not believe it is the most correct way and that I may be missing a step.
I have a simple class file in my program called clsRegistry implemented as a singleton.
public sealed class clsRegistry
{
//http://tech.pro/tutorial/625/csharp-tutorial-singleton-pattern
private static clsRegistry RegInstance;
private clsRegistry() { }
public static clsRegistry GetInstance()
{
lock (typeof(clsRegistry))
{
if (RegInstance == null)
{
RegInstance = new clsRegistry();
}
return RegInstance;
}
}
public string dataBase { get; set; }
public string userId { get; set; }
public string passWord { get; set; }
public void ReadKeys()
{
//http://stackoverflow.com/questions/1388787/information-in-registry
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Key1\Key2\Key3");
dataBase = key.GetValue("ADODataSource").ToString().Trim();
userId = key.GetValue("ServerUserID").ToString().Trim();
passWord = key.GetValue("ServerPassword").ToString().Trim();
}
} // end class definition
Which when called from the Main method implements correctly and calls the one public method (ReadKeys) in the class
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// create instance of registry class
clsRegistry regData = clsRegistry.GetInstance();
// call method
regData.ReadKeys();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new frmMain());
Application.Run(new frmLogin());
}
}
After the singleton of the class is created I have a small login form loading and I want the database name from the singleton to display in the form and this is where I have less than elegant code.
private void frmLogin_Load(object sender, EventArgs e)
{
// create a 'new' instance to the singleton?
clsRegistry regData = clsRegistry.GetInstance();
lblDataBase.Text = regData.dataBase;
}
Do I really need to create another reference to my singleton object in order to read some values (or later on call another method) or am I missing a step some where? I am operating under the assumption that once I create an instance of a class as a singleton and it remains within the same namespace I can access any public value or method. No?
For reference I am using Visual Studio 2010 and the 4.0 framework (and yes I am another classic VB developer thats FINALLY jumping ship)