Singleton Pattern and ViewModel

.net c# entity-framework mvvm


I have one ViewModel for enums handling (few entities in Entity Framework).

1) Philosophically, is it a good practice to use a SINGLETON PATTERN for this ViewModel, because it's widespread over all application and it's used on many places.

2) Isn't it a problem for ViewModel (and associated ObjectContext) to live for very long time?

Thank you!

5/31/2011 1:48:56 PM

Accepted Answer

This should probably be broken up into two separate questions, but I'll take a stab at both:

  1. No. There's no reason a ViewModel should be a Singleton. You actually WANT multiple instances (since each is going to vary) rather than a single instance that lives for the run of the application. Just because an object is widespread and is used frequently doesn't make it a good candidate for a just means that it's a good object.

  2. ViewModels should not have a very long lifetime (another reason you don't want a singleton). In MVVM, the lifespan of a given ViewModel would be as long as the user has the window open and finishes their changes.

5/31/2011 1:54:58 PM

Popular Answer

Having a singleton ViewModel is entirely valid in specific cases. One example I have used multiple times is a SettingsViewModel. Which needs to be accessed globally by multiple systems within the app. My Settings Model on creation loads up settings from a file, the ViewModel allows me to bind to modify those settings. The singleton allows me to globally access those settings where I need instead of passing them around as parameters.

Entirely valid, in this case.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow