Click here to Skip to main content
Click here to Skip to main content
Go to top

Prism Event Aggregator Service and Extension Methods

, 24 Mar 2009
Rate this:
Please Sign up or sign in to vote.
The extremely easy way to connect your code

Introduction

One of the most challenging issues I encounter in my development projects is connecting my code parts together. (By parts, I mean: User controls, Entities, External project resources and so forth). I was certain the answer to resolve this issue is using the .NET framework’s Events mechanism. I wanted to develop generic, loosely coupled and easy to use solution to create a strong infrastructure for all my projects.

Background

I suggest you take a look on the Prism event aggregator service and C# extension methods feature.
Here are the solutions I tried before I arrived at the ideal one (For easy discussion, I am presenting the solution with WPF user controls, but it still holds for other pieces of code):

  1. Wiring the parts with events – The event declaration is inside the user control. Say we have user controls A, B and C. I can declare an event inside C and register for it with A and B, then A and B can get notifications from C each time an event is raised.
    Very quickly, I left this solution because it's tightly coupled and may cause memory leak problems. The publisher and the subscriber have to know of each other which is a bad design, and a subscriber can't be collected by the GC if it's connected with the publisher with strong event reference unless you explicitly un-hook it which makes the solution even more tedious (we're here to save time, not make more work!).
  2. Using WPF event routing – Although WPF Event Routing is a very good feature in WPF, it is a WPF specific solution and I need a generic one. Also, one cannot use it everywhere even if the project is WPF.
  3. Using CAB event broking service – CAB event broking service lets you wire any parts of the code in a loosely coupled manner; it's very robust and seems suitable for my purpose. My problem with this easy solution is that my project has to be a CAB project. I can't use the Broking service out of CAB (at least I don't know how to), so it wasn't reusable for me.
  4. Prism aggregator service - The fourth solution I considered was the Event Aggregator Service shipped with the new WPF Prism project introduced by the P&P team from Microsoft. The cool thing with this service is that it is independent from using Prism based project so you can import its functionality as a standalone service. 

Inside the Solution

First I have to add for my project (Class library project) called GenericEventAggregator three DLLs which event service needs:

  • Microsoft.Practices.Composite
  • Microsoft.Practices.Composite.Wpf (Though it is named WPF, it does not rely on WPF and can be used in any project.)
  • Microsoft.Practices.ObjectBuilder2

Now I have to add a factory method class to help me access the aggregator in a simple way:

    public static class ServicesFactory
    {
    // Singleton instance of the EventAggregator service
    private static EventAggregator eventService = null;

    // Lock (sync) object
    private static object _syncRoot = new object();

    // Factory method
    public static EventAggregator EventService
    {
        get
        {
            // Lock execution thread in case of multi-threaded
            // (concurrent) access.
            lock (_syncRoot)
            {
                if (null == eventService)
                {
                    eventSerice = new EventAggregator();
                }
                // Return singleton instance
                return eventSerice;
            } // lock
        }
    }
}        

Now I need to add a generic EventArgs class that inherits from the CompositeWpfEvent class. For each event to be published, we need to join .NET object  (event value) and a topic (event topic). This way subscribers can hold the object publishers send and use the topic to filter the events shoot by the publishers.

  public class GenericEvent<tvalue /> <TValue>: CompositeWpfEvent<EventParameters<TValue>>{ }
    public class EventParameters<TValue>
    {
        public string Topic { get; private set; }
        public TValue Value { get; private set; }
    }

You see a new helper class EventParameters. This class can help to envelope any object wanted to be used with the service, and a topic of the event. I derived from Glenn Block’s article about Firing generic events with EventAggregator.

As funny as it may seems, that’s it! We don't need anything else to start using the service. You can create your project, add the GenericEventAggregator project reference and start using it. I created a standalone class library project for the coming enhancements.

Now add a new WPF project (it's only an example, you can use whatever kind of project you like) called MyEventAggregatorSeriveTest.

Add to user controls SubscriberUserControl and PublisherUserControl.

Now add the event aggregator publishing event syntax in the Button event:

ServicesFactory.EventService.GetEvent<GenericEvent<string><genericevent<string />>().Publish
	(new EventParameters<string /> { Topic = "PublisherUserControlEvent", 
	Value = "Hello Event Aggregator" });

This way we told the aggregator service to publish an event with topic PublisherUserControlEvent and a value Hello Event Aggregator.  We need the PublisherUserControlEvent string for filtering task, meaning if another control publishes an event with object string, then we have to filter subscribers for string object for listening to certain events based on the topic.

Now we have to add a subscriber to the event, so when user clicks the button, the subscriber control has to do something. We can do it in the SubscriberUserControl constructor:

ServicesFactory.EventService.GetEvent<<genericevent<string />GenericEvent<string>>().Subscribe(
s =>
{
    if (s.Topic == "PublisherUserControlEvent")
        tblockEventValue.Text = s.Value;
}
);

Here the subscriber control registers to the events with object string but can filter this event by the event’s topic.

Run the project and test it. After pressing the button, you'll see the value in the subscriber control.

That’s pretty cool; I can communicate between the two controls without any need for both controls knowing of each other.

Now you can extend the use of the service wherever you want in your projects.

Improving the Concept

After I started using the new service, all the time I ask myself, “How I can give my project objects to use the service as a method inside of them?”.
It would be very cool if I could do the following statement:

MyObject.PublishEvent(MyEventTopic) 

This statement will publish the event without any need each time to use the statement I mentioned above:

ServicesFactory.EventService.GetEvent<GenericEvent<string><genericevent<string />>().Publish
    (new EventParameters< MyObject > { Topic = MyEventTopic , Value = MyObject.value});

Suddenly, I remembered the Extensions Methods feature shipped with the C# 3.5. It came to the rescue. If I write an extension method with object type parameter and implement the publish statement, then I can achieve what I want.

So, I added an ExtensionServices class to the GenericEventAggregator project:

  
public static class ExtensionServices
    {
        //Supplying event broking mechanism to each object in the application.
public static void PublishEvent<TEventSubject>
	<teventsubject />(this TEventSubject eventArgs,string eventTopic)
       	 {            	ServicesFactory.EventService.GetEvent
					<GenericEvent<TEventSubject><genericevent<teventsubject />>()
.Publish(new EventParameters<TEventSubject><teventsubject /> { Topic= eventTopic, Value= eventArgs});
        }
    }

PublishEvent is the extension method which can be used with each object to do the service mechanism. So the PublisherUserControl publishing code will become:

"Hello Event Aggregator".PublishEvent("PublisherUserControlEvent");

Oh, that pretty nice! Now I can simply publish an event with the service in a very simple manner:

new Person().PublishEvent("Person Event") 
new DataTable.PublishEvent("Data table event") 
LinkObjectCollection.First().PublishEvent("LinkObjectEvent")

Conclusion

In this article, I presented the power of integrating the new Prism event aggregator service and the instance methods feature. All you need to start enjoying the service is adding the GenericEventAggregator DLL reference and immediately you'll start seeing the Publish event method appear in your entire projects object. All you have left to do is subscribe (and filter) and that's it.

I'll be very happy to get comments for improvements of the concept.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Wasim Farhat
Software Developer (Senior) Free lancer
Israel Israel
I'm very interested on .Net related technologies (WPF,WCF,WF,Data services, Silverlight ...) and software Architecture issues.

Comments and Discussions

 
GeneralMy vote of 2 PinmemberClifford Nelson20-Mar-12 13:47 
GeneralToo many subscribers to the same object PinmemberKostya0016-Dec-10 18:05 
GeneralMy vote of 5 Pinmemberaharon_lis29-Nov-10 1:03 
QuestionIs it possible to send objects? PinmemberDewey21-Nov-09 11:05 
AnswerRe: Is it possible to send objects? PinmemberWasim Farhat15-Feb-10 21:38 
GeneralRe: Is it possible to send objects? PinmemberDewey16-Feb-10 20:36 
GeneralNice One PinmemberMember 45654336-Nov-09 2:12 
GeneralRe: Nice One PinmemberWasim Farhat6-Nov-09 11:11 
GeneralWasim: A WPF Solution, and Silverlight Question PinmemberDewey24-May-09 21:41 
GeneralRe: Wasim: A WPF Solution, and Silverlight Question PinmemberWasim Farhat25-May-09 10:36 
GeneralRe: Wasim: A WPF Solution, and Silverlight Question PinmemberDewey25-May-09 14:18 
GeneralRe: Wasim: A WPF Solution, and Silverlight Question - I got it PinmemberDewey25-May-09 14:45 
GeneralRe: Wasim: A WPF Solution, and Silverlight Question - I got it PinmemberWasim Farhat25-May-09 21:30 
GeneralRe: Wasim: A WPF Solution, and Silverlight Question - I got it PinmemberWasim Farhat26-May-09 11:36 
GeneralRe: Wasim: A WPF Solution, and Silverlight Question - I got it & Another Benefit PinmemberDewey27-May-09 8:56 
GeneralAnd some answers for DLL Problems PinmemberDewey22-May-09 21:24 
GeneralRe: And some answers for DLL Problems PinmemberWasim Farhat23-May-09 1:00 
GeneralOne more question PinmemberDewey22-May-09 19:58 
GeneralOne question PinmemberDewey22-May-09 17:32 
AnswerRe: One question PinmemberWasim Farhat23-May-09 0:57 
GeneralRe: One question PinmemberDewey23-May-09 8:56 
GeneralGood Work !!!!!! Pinmembersafisa18-May-09 0:54 
GeneralRe: Good Work !!!!!! PinmemberWasim Farhat18-May-09 2:31 
QuestionCan this be done for Silverlight Pinmemberdavid_dublin30-Apr-09 10:41 
AnswerRe: Can this be done for Silverlight PinmemberWasim Farhat1-May-09 1:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 25 Mar 2009
Article Copyright 2009 by Wasim Farhat
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid