Search code examples
c#serializationjson.netsingleton

Break Singleton Using Serialization C#


This is my singletion class Person.

public class Person
{
    private static Person _person = null;

    private Person()
    { }

    public string Name { get; }

    public static Person PersonObj
    {
        get
        {
            if (_person == null)
                _person = new Person();

            return _person;
        }
    }
}

now i can create two instances of this class by Serialization.

static void Main(string[] args)
{
    Person p = Person.PersonObj;
    string sss = Newtonsoft.Json.JsonConvert.SerializeObject(p);
    Person p1 = JsonConvert.DeserializeObject<Person>(sss);    
    if (p != p1)
    {
           // insert here 
    }
} 

Now after Serialization I have two different object. As the class is singleton how it can have two different objects ?


Solution

  • A singleton is a programming concept - not a language feature. Its perfectly possible to create code that creates instances of classes that - in theory - should only be created by a singleton factory. You dont even need to use serialization to achieve that - just use Activator.CreateInstance().

    It might be helpful also to consider that your class constructor also doesn't have to get called; sure, if your call new MyClass() it will do, but deserialization doesn't have to call the constructor. Serialization as a concept stores and rehydrates the state of a class instance; so it doesn't need to obey other class instantiation concepts, like constructor scope or constructor logic.