Singleton Pattern and ViewModel

.net c# entity-framework mvvm


I possess oneViewModel for managing enums (few entities in Entity Framework).

1) Does using a SINGLETON PATTERN for this ViewModel, which is common across all applications and is utilized in numerous locations, represent acceptable philosophical practice?

2) Does it provide a challenge for ViewModel (and relatedObjectContext (living for a very long time)?

I'm grateful.

5/31/2011 1:48:56 PM

Accepted Answer

This should definitely be divided into two questions, but I'll try to answer both at once:

  1. No. A ViewModel shouldn't be a Singleton for any reason. Instead of having a single instance that lasts for the duration of the program, you really WANT numerous instances (as each will differ). A common or often used item does not automatically qualify as a good candidate for a singleton; it just qualifies as a good object.

  2. Another reason you don't want a singleton is because ViewModels shouldn't have a very lengthy lifespan. In MVVM, a ViewModel would remain active for the duration that the user had the window open and was making changes.

5/31/2011 1:54:58 PM

Popular Answer

In certain circumstances, having a singleton ViewModel is perfectly acceptable. A SettingsViewModel is one instance that I've used several times. It requires global access by several services inside the app. My Settings Model automatically loads settings from a file when it is created, and the ViewModel lets me bind to change those settings. Instead of having to send those settings around as arguments, the singleton enables me to access them universally anywhere I need.

In this instance, absolutely true.

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