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?

Answers


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; 
        }
    }
}

Need Your Help

JavaScript dialog return

javascript function return-value return extendscript

I've got a JavaScript function that draws a dialog. I'd like to have it return the value the user specifies. The problem is, the dialog is closed when a user clicks on of two buttons, which have o...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.