Saturday, September 26, 2009

A Twist on the Twist of the Observer Pattern

Thanks to those of you who read my Twist on the Observer pattern and gave me the feedback. You said,

"Hey, Jeremy, that's neat, but there is already a pattern established for what you're talking about, and a few great solutions ready to use. Besides, they are much, much more powerful..."

Thanks to Microsoft MVP Jason Rainwater for taking the time to give me an excellent explanation and for really delving into the inner workings of the solution.

The solution is the event aggregator pattern. For a good introduction, check out Jeremy Miller's brain dump on the topic.

The PRISM/CAL comes with its own event aggregator. It supplies a IEventAggregator that you can wire into your dependency injection container, then reference throughout the project.

In my base service class (seen by all) I create an event like this:

...
public class EntitySelectedEvent : CompositePresentationEvent<MyEntity>
{
}
...

In the view model for the module that has to "wake up" when the entity is selected, I inject the aggregator into the constructor and then do this:

...
eventAggregator.GetEvent<EntitySelectedEvent>().Subscribe(u=>this.entity=u); 
...

When the entity is selected (in a completely different module), I can simply publish:

...
eventAggregator.GetEvent<EntitySelectedEvent>().Publish(entity);
...

That's it! One module listens for the selection and reacts, not caring where/who or how it is published (which means we can publish a test entity in our unit test and test the subscription mechanism) ... while another module publishes the event and doesn't care who is out there listening.

For those of you who weren't familiar with the pattern or the implementation, I hope this helps get you excited and adds another element to your arsenal of coding techniques!

Jeremy Likness