Is it a wrong practice to make all viewModels singleton if you don't need multiple instances of each screen?
3 Answers
Yes because singletons are evil.
You will probably run into issues where the VMs are holding onto state which could be out of sync with your database and lead to excessive memory consumption. It will be much harder to unit test due to the state being persisted.

- 9,564
- 146
- 81
- 122

- 3,077
- 2
- 25
- 39
-
1My preference is to write a ViewModel singleton that provides the main ViewModel objects from which the View can easily retrieve all other ViewModel objects as required. Often this master ViewModel object provides the command implementations so the View can support opening of documents ........http://msdn.microsoft.com/en-us/magazine/ff798279.aspx , any comments? – ns12345 Feb 15 '11 at 16:12
-
The Document Manager Adapter part of that article? – Tom Dudfield Feb 15 '11 at 16:16
-
2I would look at some articles about Prism or Caliburn, and using a inversion of control framework, like Unity, to resolve and instantiate view models for you. http://msdn.microsoft.com/en-us/magazine/cc785479.aspx – Tom Dudfield Feb 15 '11 at 16:21
-
5@Tom, don't all inversion of control framework have at least one singleton in them - you have just siad that all singletons are eval – Ian Ringrose Feb 16 '11 at 10:43
-
:) It is more of a case that there are very few scenarios where [singletons are acceptable](http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/), and you should always try to look for an alternate approach. In terms of DI it is about how you manage access to your container. You should create and setup the container in the highest entry point of your application and use it it inject dependencies into objects below it, so nothing is using the DI container directly. – Tom Dudfield Feb 17 '11 at 16:30
Singletons:
- make testing harder
- give you problems later if you do need more than one of them
- are hard to control where they are created
So only use the singleton pattern if you have a very good reason to do so - "because you can" is not a good reason.

- 9,564
- 146
- 81
- 122

- 51,220
- 55
- 213
- 317
Yes.
First, you may very well be putting yourself in a corner for any extensibility, depending on the singleton implementation. Second, the design probably won't be very clean referring to static singletons everywhere. Third, unit testing will either be difficult or it won't replicate actual class usage, or both. Forth, do having singletons solve any design problems for you? If you are simply trying to save on resources then I would just forget it.

- 17,016
- 8
- 49
- 74