WEBSITE

Application Patterns and Tips : Use an Event Broker

1/12/2012 3:57:51 PM
An event broker is merely an object that acts as middleman for any number of events from any objects to any other object. In a way, this is taking the Observer Pattern  even further.

Here’s a simple event broker implementation:

public class EventBroker
{
Dictionary<string, List<Delegate>> _subscriptions =
new Dictionary<string, List<Delegate>>();

public void Register(string eventId, Delegate method)
{
//associate an event handler for an eventId
List<Delegate> delegates = null;
if (!_subscriptions.TryGetValue(eventId, out delegates))
{
delegates = new List<Delegate>();
_subscriptions[eventId] = delegates;
}
delegates.Add(method);
}

public void Unregister(string eventId, Delegate method)
{
//unassociate a specific event handler method for the eventId
List<Delegate> delegates = null;
if (_subscriptions.TryGetValue(eventId, out delegates))
{
delegates.Remove(method);
if (delegates.Count == 0)
{
_subscriptions.Remove(eventId);
}
}
}

public void OnEvent(string eventId, params object[] args)
{
//call all event handlers for the given eventId
List<Delegate> delegates = null;
if (_subscriptions.TryGetValue(eventId, out delegates))
{
foreach (Delegate del in delegates)
{
if (del.Method != null)
{
if (del.Target != null)
{
del.DynamicInvoke(args);
}
}
}
}
}
}


Usage is very simple: Rather than raising normal .NET events, just call the appropriate methods on the EventBroker. The project contains three user controls: One of them raises the event and the other two listen for it. A form owns the event broker and ties everything together, as the following partial code example shows:

public partial class Form1 : Form
{
//a single event broker to tie all controls together
EventBroker _broker = new EventBroker();

public Form1()
{
InitializeComponent();

myControl11.SetEventBroker(_broker);
myControl21.SetEventBroker(_broker);
myControl31.SetEventBroker(_broker);
}
}
public partial class MyControl1 : UserControl
{
EventBroker _broker;

public MyControl1()
{
InitializeComponent();
}

public void SetEventBroker(EventBroker broker)
{
_broker = broker;
}

//when user clicks button, fire the global event
private void buttonTrigger_Click(object sender, EventArgs e)
{
if (_broker != null)
{
_broker.OnEvent("MyEvent");
}
}
}

public partial class MyControl2 : UserControl
{
EventBroker _broker;

public MyControl2()
{
InitializeComponent();
}

public void SetEventBroker(EventBroker broker)
{
_broker = broker;
_broker.Register("MyEvent", new MethodInvoker(OnMyEvent));
}

private void OnMyEvent()
{
labelResult.Text = "Event triggered!";
}
}
//MyControl3 is the same as MyControl2


See the EventBroker sample for the full source.

Using this method gives you a few advantages:

  • Because strings are used, any component can publish or subscribe to any event without having to add a reference to a strongly typed object.

  • Because no component knows anything about the origin or destination of events, it is trivial to add or remove components with breaking dependencies.

Note

This method is most appropriate for global events that you need to communicate across the entire application, and passing objects around complicated code hierarchies just to listen for events is not worth the headache and maintenance problems that are entailed. For more local events, you should definitely just use the normal .NET event pattern.

Other  
  •  AJAX : Updating Progress
  •  AJAX : The Timer
  •  Getting Familiar with AJAX
  •  ASP.NET Server-Side Support for AJAX & AJAX Client Support
  •  ASP.NET and AJAX
  •  IIS 7.0 : Securing Communications with Secure Socket Layer (SSL)
  •  ASP.NET 4 : Getting More Advanced with the Entity Framework (part 2) - Updates, Inserts, and Deletes
  •  ASP.NET 4 : Getting More Advanced with the Entity Framework (part 1) - Querying with LINQ to Entities
  •  IIS 7.0 : Implementing Access Control - Authentication (part 4)
  •  IIS 7.0 : Implementing Access Control - Authentication (part 3) - IIS Client Certificate Mapping Authentication
  •  IIS 7.0 : Implementing Access Control - Authentication (part 2) - Digest Authentication & Windows Authentication
  •  IIS 7.0 : Implementing Access Control - Authentication (part 1)
  •  IIS 7.0 : Implementing Access Control - NTFS ACL-based Authorization & URL Authorization
  •  IIS 7.0 : Implementing Access Control - Request Filtering
  •  IIS 7.0 : Implementing Access Control - IP and Domain Restrictions
  •  IIS 7.0 : Implementing Security Strategies - Configuring Applications for Least Privilege
  •  Security Changes in IIS 7.0 : Reducing the Application’s Surface Area
  •  Advanced ASP.NET : The Entity Framework (part 3) - Handling Errors & Navigating Relationships
  •  Advanced ASP.NET : The Entity Framework (part 2)
  •  Advanced ASP.NET : The Entity Framework (part 1) - Creating an Entity Data Model
  •  
    Top 10
    Beginning Android 3 : Working with Containers - Scrollwork
    DirectX 10 Game Programming : Direct3D Fonts
    Customizing Windows 7’s Desktop (part 3) - Getting Around the Taskbar
    Publishing ASP.NET Web Applications : MSDeploy Publish
    Parallel Programming : Task Relationships (part 2) - Parent and Child Tasks
    Secure Browsing and Local Machine Lockdown in Vista
    SQL Server 2005 Data Protection
    SharePoint 2010 : Identifying Isolation Approaches to SharePoint Security
    Programming Microsoft SQL Server 2005 : FOR XML Commands (part 3) - OPENXML Enhancements in SQL Server 2005
    Windows 7 : Installing and Configuring Windows Media Center Using the Wizard
    Most View
    Optimizing for Vertical Search : Optimizing for Image Search (part 2) - Optimizing Through Flickr and Other Image Sharing Sites
    Exchange Server 2010 : Installing OCS 2007 R2 (part 1) - Extending the Active Directory (AD) Schema & Preparing the AD Forest
    Get to a SharePoint Site
    Mouse Events in Silverlight
    Programming the Mobile Web : Content Delivery (part 3)
    # Oracle Coherence 3.5 : Achieving Performance, Scalability, and Availability Objectives (part 2)
    Programming Hashing Algorithms (part 4) - Hashing Streamed Data
    Programmatic Security (part 6) - Assembly-Wide Permissions
    The Hello-World Midlet
    Silverlight Recipes : Updating the UI from a Background Thread
    Windows 7: Getting into Your Multimedia (part 1) - Configuring Windows Media Player for the First Use
    Windows Phone 7 Development : Media - Adding Sounds to an Application
    Windows Phone 7 Development : Push Notifications - Implementing Raw Notifications
    ActiveX Installer Service in Windows Vista
    Windows Mobile Security - Local Data Storage
    iPhone Application Development : Creating and Managing Image Animations and Sliders (part 3) - Finishing the Interface
    Communicate over the Internet (WCF)
    Performing a typical Exchange Server 2010 install
    Sharepoint 2007: Add a Column to a List or Document Library
    Application Security in Windows Vista