Search code examples
c#windows-phone-8windows-phone

Global scope object between pages in Windows Phone App


I have two static classes called "xxxManager". I initialize them when the "MainPage" starts, they take from memory some data to be represented in my app, in particular go into a list. I created them as static classes because I need their data in every page of my app. So I just do:

xxxManager.GetDataByPageId(2).GetList() and I can use all of its values.

The problem is that I don't want them to be static because I want to create an abstract class and use to derive my two "Managers". If I would do this, I will need to create a constructor of those classes, but I don't want to do a new every time I go in another page, because it would read another time from memory every data.

How can I put an object into the global scope of all my app, through pages?

I thought to create a static class (just an example):

public static Definitions()
{
     xxxManager manager_;

     public void Initialize()
     {
          xxxManager manager_ = new xxxManager();
     }
}

Is it a good solution, or is there something better?


Solution

  • From what I understand, you need an implementation of the singleton pattern.

    public class XxxManager
    {
        private static Lazy<XxxManager> lazyInstance = new Lazy<XxxManager>(() => new XxxManager());
    
        private XxxManager() 
        {
        }
    
        public static XxxManager Instance
        {
            get
            {
                return lazyInstance.Instance;
            }
        }
    }
    

    From there, you can retrieve your manager anywhere from your code by calling XxxManager.Instance. The constructor of the class is set to private to make sure it's never instantiated manually.