Persisting View State via the ViewModel

Any Enterprise grade application you design will have a requirement to persist state. Say in your architecture, you have an implementation where all ViewModels subscribe to an ApplicationClosingEvent and then submit their profile to some implementation of an IProfileService. Upon application start-up, each ViewModel is presented with its saved state, by some profile service, cataloged by name.

So, what do you serialize and present as state? Well, since you already have a ViewModel, there is temptation to just serialize it, assuming it is serializable and pass this on to the profile service.

However, I prefer a different approach. For each ViewModel that has potentially serializable content, I make it implement an interface ISettingsContributor that has a single method GetPersistInfo(). This interface is defined as follows:

  public interface IPersistentUserSettingsContributor
    {
        PersistInfo GetSettingstoPersist();
        void LoadedPersistedSettings(PersistInfo persistInfo);
    }

Then I implement this in the base ViewModel class as abstract and force all ViewModels to provide an implementation. These methods can then be called by the framework to persist and restore state.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s