Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static ViewModels vs instanced ViewModels

I have two views that share one observable collection from certain viewmodel, but with different collection view parameters. What is the correct way of implementing it in MVVM Light? Is there any support for non-static VMs? How can I manage their lifetime and dispose them?

like image 610
Ian Thompson Avatar asked May 13 '11 10:05

Ian Thompson


1 Answers

There is!

By default objects resolved from the SimpleIoc are singletons. To get around this you need to pass a unique identifier as a parameter of the ServiceLocator.GetInstance method.

See below:

We have two properties returning the same viewmodel. One returns a singleton and the other will return a new instance each time.

class ViewModelLocator
{
    static ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
        if (ViewModelBase.IsInDesignModeStatic)
        {
            SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
        }
        else
        {
            SimpleIoc.Default.Register<IDataService, DataService>();
        }

        SimpleIoc.Default.Register<MainViewModel>();
        SimpleIoc.Default.Register<SecondViewModel>();
    }


    public MainViewModel MainAsSingleton
    {
        get { return ServiceLocator.Current.GetInstance<MainViewModel>(); }
    }

    public MainViewModel MainAsDiffrentInstanceEachTime
    {
        get { return ServiceLocator.Current.GetInstance<MainViewModel>(Guid.NewGuid().ToString()); }
    }
}
like image 66
Faster Solutions Avatar answered Oct 05 '22 11:10

Faster Solutions