首页 > 解决方案 > Accessing same singleton instance and destroying it when it is not required

问题描述

(WPF MVVM)

I have a requirement where I need to access the same instance (following Singleton pattern) and also I want to create/access refreshed instance of above instance.

So what I did is, use singleton pattern(for both Model and ViewModel) at the required time and then destroy it (by setting the instance to value .i.e., giving Singleton.Instance = null) when I need new/refreshed version above Instance as the old object has been already stored in my ObservableCollection.

public sealed class SingletonViewModel
{
   private static SingletonViewModel instance=null;

   private SingletonViewModel ()
   {
   }

   public static SingletonViewModel Instance
   {
     get
     {
        if (instance==null)
        {
            instance = new SingletonViewModel ();
        }
        return instance;
      }
      set
      {
        instance = value;
      }
 }
 //I have an ObservableCollection of the SingletonViewModel class in other class. 
 //I am destroying the above instance by setting the Instance value to null.
  public void Destroy{
   SingletonModel.Instance = null;
   SingletonViewModel .Instance = null;
  }
 
  public String Header{
    get return SingletonModel.Instance.Header;
    set { SingletonModel.Instance.Header = value}
  }

Though I destroy and try to access the above instance after calling function Destroy, my ObservableCollection is getting updated with the recent value of the above Instance.

标签: c#wpfserializationmvvmsingleton

解决方案


推荐阅读