views:

405

answers:

1

Hi there,

When using a Service Locator class to serve up ViewModels for your WPF pages to bind to. Should the ViewModels be Singleton scoped or Factory scoped? Is one generally a better idea for WPF applications??

I'm aware that in Silverlight, Singleton lends itself better to pages which are User Controls and are only moved into and out of the foreground. But up until trying to apply this pattern, i've been newing up instances of pages and their respective VMs everytime they are to be loaded.

Me and my colleague have gone through all the pluses and minuses for each option and theres nothing screaming out which is the better option for our scenario.

Thanks.

+2  A: 

I would stay away from making your View Models singletons. Unless they are views that are persisted in a region for the entire user session. Things like navigation, or menus etc. If you use something the Prism/Composite WPF they leverage Unity as the IoC or Service Locator(if that is how you use it), View Models/Presentation Models are created when presented and left for garbage collection when closed. This allows each screen to go through its lifecycle as intended.

You can use things like the RegionManager (CompositeWPF) to hold the View Models in memory until they are explicitly closed. This will allow users to tab through open views maintaining the their interactions if this is a requirement. When the user decides to save/close a screen it gets removed from the RegionManager and is then garbage collected.

Singletons are design patterns used for a very specific purposes i.e. you need only one, and will only need one for the lifetime of the application. If that is not the requirement I would stay away.

Brette.Net