• Elegant Code Cast


    View in iTunes Any Podcatcher

Unity 1.0 EventBroker Sample CAB Style

Ok so Unity 1.0 has shipped, or should I say the “Unity Application Block” as Microsoft is terming it now. However, in this post I am not going to talk about the Unity IoC contain but a pretty cool peace of code that comes bundled with Unity’s QuickStart samples, the Event Broker Extension.

The Event Broker Extension QuickStart demonstrates how you can extend the Unity container by adding a custom extension. The QuickStart implements an Event Broker for the container as a container extension and demonstrates the new extension using the StopLight QuickStart application sample.

The Event Broker Extension QuickStart contains three projects:

  • EventBroker. This project implements a simple publish and subscribe mechanism that supports multiple event publishers and multiple subscribers.
  • EventBrokerExtension. This project implements the custom container extension that allows applications to publish and subscribe to events using attributes or explicitly using code.
  • StopLight. This project is basically the same as that described in the Unity StopLight QuickStart, but it uses the custom container extension to manage the publishing of, and subscription to, two events within the application.

Now, why is this Unity EventBroker interesting? Well, if you have ever worked with CAB (Composite UI Application Block) or SCSF (Smart Client Software Factory) then you know one of its main pillars was the implementation of a nice Pub/Sub event subscription framework which Microsoft called Event Broker. This was one of the best things about CAB. Unfortunately with CAB it is an all or nothing deal. You really cannot use the CAB Event Broker without using the rest of the CAB underpinnings.

The Unity implementation of the Event Broker is similar to CABs so you should feel right at home if you have any experience with CAB or SCSF. The one huge benefit is that the Unity Event Broker can easily be integrated into any existing WinForm or WPF application where you would like an easy to manage Event bus to handle all your event traffic.

It really is easy to implement, lets take a look at what you need to do in order to integrate the Unity based Event Broker into your application.

1) Download Unity 1.0 install it and unzip the “Unity QuickStart” package found in the Unity start menu installation path.

2) Compile the EventBrokerExtention and SimpleEventBroker projects.  Then grab the following DLLs found in the EventBrokerExtention bin folder and reference them in your application.
  EventBrokerExtension.dll
  SimpleEventBroker.dll
  Microsoft.Practices.ObjectBuilder2.dll
  Microsoft.Practices.Unity.dll

3) Now open your WinForm application and modify your entry point usually the Program.cs file which in my demo calls the FormMain.cs using a Unity Container like so.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using EventBrokerExtension;
using Microsoft.Practices.Unity; 

namespace SampleWinApp
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false); 

            // Create parent container
            IUnityContainer mainContainer = new UnityContainer()
                  .AddNewExtension<EventBrokerBusExtension>(); 

            Application.Run(mainContainer.Resolve<FormMain>());
        }
    }
}

The important thing to notice is that I have wired up the EventBrokerExtention class through the Unity AddNewExtention method.  This will cause all the Events that are properly decorated with the correct attributes to be automatically registered in the EventBroker or SimpleEventBroker class.

You will also want to go and modified all the areas in your code where you are opening other forms to use a Unity container as well.  Here is an example opening a Form called FromA.cs 

//Create container
IUnityContainer myContainer = new UnityContainer()
           .AddNewExtension<EventBrokerBusExtension>();
//Open Form
FormA newForm = myContainer.Resolve<FormA>();
newForm.Show();

Oh, make sure you import the proper libraries on all your forms.

using Microsoft.Practices.Unity;
using EventBrokerExtension;
using SimpleEventBroker;

Now you need to setup all the Event publications and triggers. Let’s start simple, say we have a button on our FormMain that is used to force a data refresh in your application. You would need to add a publish event to your page like so.

//Using an attribute register an event in the EventBroker
[Publishes("RefreshData")]
public event EventHandler RefreshData ;
//Method you will call to trigger the event in the EventBroker 
public virtual void OnRefreshDataChange(object sender, EventArgs ea)
{
    EventHandler handlers = RefreshData ;
    if (handlers != null)
    {
        handlers(this, EventArgs.Empty);
    }
}

On your button click trigger the event like so.

private void buttonRefresh_Click(object sender, EventArgs e)
{
    //Trigger your event 
    OnRefreshDataChange(this, e);
}

Now you need to setup all your Event subscriptions, this is supper easy.  You will need to create a method on all the forms in your application that will handle your refresh command i.e. implements the functionality you wish for each form or control in your application.  So far in this contrived example I have two forms FormMain and FormA.  You would add a method like so to each page.    

[SubscribesTo("RefreshData")]
public void OnRefreshDataFired(object sender, EventArgs e)
{
         //Do something, we need to do a data refresh
}

Now anytime the RefreshData button is pushed the event is fired and all objects subscribed to that event in the EventBroker will be triggered. 

One important step you will want to do is unregister your subscribed events every time a modal form is closed.  Remember we are using the Unity IoC container to open a form which automatically registers all publisher and subscriber event handles on form_load (opened). 

// Unregister your subscription to help prevent runtime errors
private void FormA_FormClosing(object sender, FormClosingEventArgs e)
{
     EventBroker myEB = new EventBroker();
     myEB.UnregisterSubscriber("RefreshData", OnRefreshDataFired);
}

That is about it, I used this to clean up an old legacy application that had Window events thrown everywhere.  The SimpleEventBroker class has several methods you can use to monitor what is going on inside the EventBroker such as GetPublisher, GetSubscribers, etc.

Oh, in my implementation I modified the Dictionary in the SimpleEventBroker class which holds the registered published events to be static, makes it easier if you have lots of modal forms, just make sure the Keys (string values) are unique.


public class EventBroker
    {
        private static Dictionary<string, PublishedEvent> eventPublishers  

        = new Dictionary<string, PublishedEvent>();
kick it on DotNetKicks.com

2 Responses to “Unity 1.0 EventBroker Sample CAB Style”

  1. [...] Unity 1.0 EventBroker Sample CAB Style - Scott Nichols highlights the Event Broker that comes with Unity and shows how you can integrate it with your applications. [...]

  2. Could you please provide the sourcecode? What is “EventBrokerBusExtension”?

Leave a Reply

Close
E-mail It