Here is the full source code for Event Broker Implementation in C#. In zipped file you can find EventBroker with associated tests ans simple sample application that describes how loosely coupled objects can exchange data in any host.
EventBroker Internals
EventBroker is implemented as Singleton. That ensures that all class instances communicates with one and only one instance of EventBroker. Singleton pattern is implemneted by using private constructor and public instance accessor
private static volatile EventBroker instance;
private static object syncRoot = new Object();
private static Dictionary<string, List<Delegate>> subscriptions;
private EventBroker()
{
}
public static EventBroker Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new EventBroker();
subscriptions = new Dictionary<string, List<Delegate>>();
}
}
}
return instance;
}
}
Event Broker holds internal list of subscriptions. Subscriptions are stored as generic Dictionary with string key and list of delegates that points to event handlers.
private static Dictionary<string, List<Delegate>> subscriptions;
Subscribing To Event
When someone subscribs to event it pass event ID and delegate to Event Broker. Event broker uses EventID to locate generic list of Delegates associated with that key and to add Delegate to the List.
EventBroker
.Subscribe("event://EventName", new GlobalEventHandler(Event));
public
void Event(object sender, GlobalEventEventArgs e)
{
//Do some work!
}
It is important to note that event name can be any valid string (It's just a key). We used URI notation to simplify unique naming of events.
Firing an Event
Publisher is component that notifies EventBroker that some event has occured. EventBroker will iterate trough list of delegatesassociated with event nameand invoke each one of them passing event data received from publisher. It will give opportunity to subscribersto act based on received data. Simple scenario is a CustomerList control. Each time user change customer selection, CustomerList can raise event and Event Broker will notify all subscribers. Subscribers are controls that presents differend data associated with selected customer.
publisher.FireEvent(eventname,
new GlobalEventEventArgs(expected));