Singleton constructor question
I created a Singleton class in C # with a public property that I want to initialize the first time I call the Singleton.
This is the code I wrote:
public class BL
{
private ISessionFactory _sessionFactory;
public ISessionFactory SessionFactory
{
get { return _sessionFactory; }
set { _sessionFactory = value; }
}
private BL()
{
SessionFactory = Dal.SessionFactory.CreateSessionFactory();
}
private object thisLock = new object();
private BL _instance = null;
public BL Instance
{
get
{
lock (thisLock)
{
if (_instance == null)
{
_instance = new BL();
}
return _instance;
}
}
}
}
As far as I know, when I first reference the BL instance object in the BL class, it has to load the constructor and initialize the SessionFactory object.
But when I try: BL.Instance.SessionFactory.OpenSession (); I am getting Null Reference Exception and see that SessionFactory is null ...
why?
+2
a source to share
1 answer
This is not a singleton. You should link to the excellent guide to singletons in C # . For example, use this pattern:
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Note in particular that the instance is static.
+3
a source to share