R – Singleton Pattern in .Net is not possible

design-patternsnetsingleton

I have a very interesting situation , i have figured out that Singleton pattern is not all possible with .net framework (Any version)

look at this code below

namespace SingletonPattern
{
    class Singleton
    {
    private static readonly Singleton instance = new Singleton();
    private static int mcount = 0;

    private Singleton() {

        mcount += 1;
        Console.WriteLine("Creating {0} instances of Singleton Class", mcount.ToString());
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

class program
{
    static void Main()
    {
        for (int i = 0; i < 1000; i++)
        {
            System.Activator.CreateInstance(Type.GetType("SingletonPattern.Singleton"), true);
        }

        Console.ReadLine();


        }
    }
}

with the help of System.activator any buddy can break singleton pattern.

so who's at risk ?

any guy who wrote some licensing component where license is implemented as a singleton pattern.

Any server based code which makes use of Singleton pattern.

Maybe I am wrong or my discovery does not make sense but i just wanna share and want to know your views?

Best Answer

Just because it is possible to deliberately circumvent a pattern in this way does not mean that the pattern itself is "not possible".