I need a confirmation about a singleton pattern.
I've a singleton class and I'm using it as dll. I write a program with a reference to this dll and I call my singleton class. I write a second program and I do the same.
Am I right if I tell you that even if I have two program they call both a single instance of my singleton class?
I tried to increment an static variable instancenumber that increment each time I pass the constructor and both programs tell me that the instancenumber is 1. So it should be ok but I need your advice to be sure.
Thank you. best regards
Class Singleton:
namespace SingletonClassLib
{
public class SingletonClass
{
public static int InstanceNumber = 0;
private static string myName;
#region //Singleton initialisation
private SingletonClass() { createInstance(); }
private void createInstance()
{
InstanceNumber++;
myName = myName + InstanceNumber.ToString();
}
public static SingletonClass _I { get { return NTCSession._i; } }
private class NTCSession
{
static NTCSession() { }
internal static readonly SingletonClass _i = new SingletonClass();
}
private static List<WeakReference> instances = new List<WeakReference>();
#endregion //Singleton initialisation
public static string askname { get { return myName; } }
}
}
Program 1:
using System.Windows.Forms;
using SingletonClassLib;
namespace Singletontest
{
public partial class Form1 : Form
{
SingletonClass myclass = SingletonClass._I;
public Form1()
{
InitializeComponent();
string Name = SingletonClass.askname;
MessageBox.Show("Program first: "+Name);
}
}
}
Program 2:
using System.Windows.Forms;
using SingletonClassLib;
namespace Singletontest
{
public partial class Form1 : Form
{
SingletonClass myclass = SingletonClass._I;
public Form1()
{
InitializeComponent();
string Name = SingletonClass.askname;
MessageBox.Show("Program second: "+Name);
}
}
}
As other answers suggest, the singleton instance is not shared between the two programs. Each program runs in its own OS process that has its own DLL copy