Eager Instantiation of ViewModels with MVVM Light Messaging

Nobody's Listening

Dependency registration in SimpleIoc, by default uses Lazy Instantiation, meaning the object won’t be created until it is requested, in this case, via the property on the ViewModelLocator class.

Due to configuring subscription of a message type in the Constructors of my ViewModels in MVVM Light I recently came across a situation whereby messages were being published prior to them having been subscribed to, meaning that the messages disappeared into the void unhandled.  The ViewModels relating to the pages I had navigated to were available in the ServiceLocator, but the pages that I hadn’t navigated to were not being instantiated.

Nobody's Listening
Nobody’s Listening

I needed to change this behaviour, and handily SimpleIoc provides a way to do this at the point of registration.

Instead of the default :

[csharp]
SimpleIoc.Default.Register<MainViewModel>();
[/csharp]

simply use:

[csharp]
SimpleIoc.Default.Register<MainViewModel>(true);
[/csharp]

This sets the createInstanceImmediately parameter in the Register method, meaning that the ViewModel is now Eagerly Instantiated and available in the ServiceLocator, or notably in our case, our messages have been subscribed to via the constructors at this point.

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