Thursday, April 22, 2010

Using an Observable while still supporting multiple ViewModel instances

This post follows on from my previous post, Using the Observable for Change Notification in Calculated/Dependent Properties.

An upcoming project has the need for the Views in a module to be loaded multiple times in potentially many different places in the Shell. This made me realise the shortcoming of my post that describes using an Observable to share data between Views. The problem is in how the module registers the Observable. The code is below:

protected void RegisterViewsAndServices()
{
...
_container.RegisterInstance(
_container.Resolve<ISelectedContactObservable>());
...
}


This works well in the example project give in my previous post, but it all goes awry when we want to load multiple instances of our Views, because each instance of the View will needs its own Observable. By registering an instance with Unity in this way, our hands are tied.


So what to do instead? Well, following on from another previous post, we can use a controller to overcome this limitation. The controller becomes responsible for calling Unity and obtaining our Views. At this time it can therefore also create a fresh instance of the Observable and supply it to the ViewModels. The code from the attached project (at the end of this post) looks like this:


public class MainModuleController :
IMainModuleController
{
...
/// <summary>
/// Listens for requests to load the View
/// into a Region.
/// </summary>
///
public void LoadViewsEventHandler(
LoadViewsEventArgs payload)
{
// Create a fresh Observable that is used to share data
// between the two Views
ISelectedContactObservable observable =
_container.Resolve<ISelectedContactObservable>();
observable.SelectedContact = null;

// Create the Views using Unity
...
// Assign the Observable to each of them
detailsViewModel.SelectedContact = observable;
selectionViewModel.SelectedContact = observable;
...
}
}


Using the controller this way ensures correct creation of Observable classes.


The sample project can be downloaded here
.

No comments:

Post a Comment