Mediator and events

Nov 18, 2009 at 8:48 PM

Josh, I had what I thought might be an interesting although nowhere near thought out idea, and was wondering what you might think of it...:

One of the things that I like about the mediator pattern is that it allows for automatic subscription to events based on the metadata, without concern for deregistering since you're using weak references.  Now, it occurred to me, that usually regular CLR events follow a fixed number of parameters pattern, where you have (object sender, TEventArgs args) where TEventArgs is some class derived from EventArgs.  The mediator follows a similar pattern, though it is a little different - you can have zero or one parameters, the parameter has no type restriction (that I've noticed) and you use a string as a discriminator to match up the event published to the subscribing actions.

Well...

How about providing a Subscribe method on the mediator which automatically subscribes to all events (using reflection) on a source object which follow the described pattern (always two parameters with the first being object sender, and the second being derived from EventArgs).

Then have metadata attributes which allow you to identify which events you want routed to which methods (for the Register call).

You could probably use the existing MediatorMessageSink attribute, and match the string event discriminator to the name of the published event.  There are some things I think you'd want to add - for example, allow the methods which receive the events to have a third parameter of type object, in which case you can pass the object parameter to them.  I think you might also want to add another parameter to the metadata attribute which allows specification of the type of source object - that way if the same mediator is subscribed to events from different types of source object, you could require the mediator to only route events to recepients which specify a matching source type.

What do you think? Crazy? Interesting? 

Coordinator
Nov 18, 2009 at 10:21 PM

That sounds interesting, though quite "black magical."  I can see how that would be useful, but I like to avoid adding black magic to my code, because it makes debugging and (re)learning the code more difficult.  But, if you create it, let me know!!

Nov 19, 2009 at 1:37 PM

Will do.  I may end up modifying the mediator to support this - I currently have a business object which raises events that currently have to then get forwarded on by a single 'main' viewmodel to a bunch of child viewmodels, which is how this idea cropped up - I was pondering how to avoid having to write so much glue code between the business object and the viewmodels.

Anyway, will let you know if I do modify it.

Cheers!

Phil