Loose Coupling using EventAggregation

Based on Jeremy Miller's Braindump on the Event Aggregator Pattern TecX contains an implementation of the suggestions made in that blog post.

Declare a class that implements ISubscribeTo<TMessage> and register an instance of that class with the EventAggregator.

public class Subscriber : ISubscribeTo<MyMessage>
{
  public void Handle(MyMessage message)
  {
    Console.WriteLine(message.Text);
  }
}
public class MyMessage
{
  public string Text { get; set; }
}
IEventAggregator ea = new EventAggregator();
Subscriber subscriber = new Subscriber();
ea.Subscribe(subscriber);
ea.Publish(new MyMessage { Text = "Hello World!" };

That's it. The EventAggregator will take care of thread marshalling for you.

To add even more convenience you can use Unity to auto-wire subscribers with the EventAggregator

IUnityContainer container = new UnityContainer();
container.AddNewExtension<EventAggregatorExtension>();
Subscriber subscriber = container.Resolve<Subscriber>();
IEventAggregator ea = container.Resolve<IEventAggregator>();
ea.Publish(new MyMessage("Hello World!");

See the TecX.Event and TecX.Event.Unity projects for the source code and TecX.Event.Test and TecX.Event.Unity.Test projects for usage samples.

Last edited Apr 16, 2012 at 6:45 AM by weberse, version 3

Comments

No comments yet.