Creating a Custom EventAggregator Class

Posted by Phil on Stack Overflow See other posts from Stack Overflow or by Phil
Published on 2010-04-16T03:47:38Z Indexed on 2010/04/16 3:53 UTC
Read the original article Hit count: 816

Filed under:
|
|
|
|

One thing I noticed about Microsoft's Composite Application Guidance is that the EventAggregator class is a little inflexible. I say that because getting a particular event from the EventAggregator involves identifying the event by its type like so:

_eventAggregator.GetEvent<MyEventType>();

But what if you want different events of the same type? For example, if a developer wants to add a new event to his application of type CompositePresentationEvent<int>, he would have to create a new class that derives from CompositePresentationEvent<int> in a shared library somewhere just to keep it separate from any other events of the same type. In a large application, that's a lot of little two-line classes like the following:

public class StuffHappenedEvent : CompositePresentationEvent<int>
{}

public class OtherStuffHappenedEvent : CompositePresentationEvent<int>
{}

I don't really like that approach. It almost feels dirty to me, partially because I don't want a million two-line event classes sitting around in my infrastructure dll. What if I designed my own simple event aggregator that identified events by an event ID rather than the event type? For example, I could have an enum such as the following:

public enum EventId
{
    StuffHappened,
    OtherStuffHappened,
    YetMoreStuffHappened
}

And my new event aggregator class could use the EventId enum (or a more general object) as a key to identify events in the following way:

_eventAggregator.GetEvent<CompositePresentationEvent<int>>(EventId.StuffHappened);
_eventAggregator.GetEvent<CompositePresentationEvent<int>>(EventId.OtherStuffHappened);

Is this good design for the long run? One thing I noticed is that this reduces type safety. In a large application, is this really as important of a concern as I think it is? Do you think there could be a better alternative design?

© Stack Overflow or respective owner

Related posts about cag

Related posts about design