Saturday, May 9, 2009

MVVM Developing a generic Mediator class

When I tried to separate the MVVM related classes to a different project called ‘MVVM.Core’ for future use,I came to see one issue.That is the mediator which I used is handling messages which are specific to my project.’GameOver’,’GameStarted’ etc…This would not be the case in my future projects.There the messages may be ‘UserAdded’,’UserDeleted’ or something else.So I decided to make the existing Mediator class generic.
The MultiDictionary remains the same as in MVVM Mediator Pattern(This is the place where I got Mediator code.Thanks to Sacha Barber).The changes are mainly in the Mediator class.I removed the ViewModelMessage enum (specific to my project)from that class and made it coming as generic type parameter T .Changed all references of ViewModelMessage into T.The below code snippets tell the difference.

public sealed class Mediator
{...}


public sealed class Mediator<T>
{...}

Then I had to change the view model hierarchy.I created a new Viewmodel which is called MediatorEnabledViewModel to contain the Mediator functionality.



public class MediatorEnabledViewModel<T>:WorkspaceViewModel
{
public Mediator<T> Mediator
{
get
{
return Mediator<T>.Instance;
}
}
}

These classes are in MVVM.Core project and in the application specific viewmodel project, I added one more base viewmodel which is more specific to the application where I specify the type of generic parameter T.



public class DemoAppViewModelBase : MediatorEnabledViewModel<ViewModelMessages>
{
public CustomerRepository CustomerRepository
{
get { return CustomerRepository.SingleTon; }
}
}

Now its all set.We can change the type of the message which mediator handles from the application’s view-model according to the nature of the application.Type of the message can be any enum which contains application specific values / messages.Below is the screenshot of solution structure.



The entire mediator code can be downloaded from here

No comments:

Post a Comment