wince
wince

Reputation: 531

How to Save/Load singleton class

I have configuration entity in my .NET CF application and I want to use singleton for this. Configuration can be changed and has to be saved/restored for next time application launch. I want to use xml serialize/deserialize, it also provides a possibility to change configuration over xml file. The question is how to save and restore singleton? Deserialization creates a new instance of singleton class, but it means that it will be two instances of the singleton class at the moment.

I have found a solution with ISerializable interface, but it seems that it does not work with compact framework http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable%28v=VS.90%29.aspx

Is there any way to obtain the same behavior with .NET CF?

Upvotes: 1

Views: 2446

Answers (1)

ctacke
ctacke

Reputation: 67178

Your singleton most likely uses a private constructor in its pattern. So you'd do something like this:

public class MySingleton
{
    private static MySingleton m_instance;

    private MySingleton() { }

    public static MySingleton Instance 
    { 
        get 
        {
             if(m_instance == null)
             {
                 // hydrate m_instance from serialized version
             } 
             return m_instance; 
        }
    }
}

or this:

public class MySingleton
{
    private static MySingleton m_instance;

    private MySingleton() 
    {
        // load data from config file 
    }

    public static MySingleton Instance 
    { 
        get 
        {
             if(m_instance == null)
             {
                 m_instance = new MySingleton();
             } 
             return m_instance; 
        }
    }
}

Upvotes: 3

Related Questions