0
votes

I'm a c# developer.

I have confused with private constructor and static constructor in singleton pattern.

Here is my sample code in below:

standard singleton pattern and it is thread safe:

public class SingletonTest
{
    private static readonly Lazy<RedisCacheManager> CacheManager = new Lazy<RedisCacheManager>(() => new RedisCacheManager());

    /// <summary>
    /// singleton pattern
    /// </summary>
    private SingletonTest() { }

    public static RedisCacheManager Instance
    {
        get { return CacheManager.Value; }
    }
}

second it changed the private constructor to static constructor:

public class SingletonTest
{
    private static readonly Lazy<RedisCacheManager> CacheManager = new Lazy<RedisCacheManager>(() => new RedisCacheManager());

    /// <summary>
    /// static(single object in our application)
    /// </summary>
    static SingletonTest() { }

    public static RedisCacheManager Instance
    {
        get { return CacheManager.Value; }
    }
}

And my question is the second code still one of the singleton pattern or just it always keep a only one object(RedisCacheManager) in our application? Somebody help me,thanks.

1
There is no such thing as a 'static constructor'.user207421
look at this linkAllen

1 Answers

1
votes

So to answer you question, we need to go to basic.

Static constructors have the following properties:

  1. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  2. A static constructor cannot be called directly.
  3. If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

But for standard singleton pattern

  1. It will be loaded, when we call it. So we have control over, when the singleton object will be created.
  2. User has complete control when to call it.

Hope it answers your question.