C# – ViewModel and Singleton Pattern

centity-frameworkmvvmnet

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!

Best 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 singleton...it 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.