Background event handling in Prism

Spread the love

Prism’s event aggregator is great for decoupling UI state changes when UI events occur, but sometimes you need to perform some larger, long-running task on a background thread — uploading a file, for example.

Here’s a quick example of an encapsulated event handler listening off the Prism event bus, and using Windsor’s IStartable facility to handle event subscription:

public class TradeCancelledEventHandler : ICompositePresentationEventHandler, IStartable{    private readonly IEventAggregator eventAggregator;    protected TradeCancelledEventHandler(IEventAggregator eventAggregator)    {        if (eventAggregator == null)            throw new ArgumentNullException("eventAggregator");        this.eventAggregator = eventAggregator;    }    public void Start()    {        // Register to receive events on the background thread        eventAggregator            .GetEvent<TradeCancelledEvent>()            .Subscribe(Handle, ThreadOption.BackgroundThread);    }    public void Stop()    {        eventAggregator            .GetEvent<TradeCancelledEvent>()            .Unsubscribe(Handle);    }    void Handle(TradeCancelledEventArgs eventArgs)    {        // ... do stuff with the event    }}

Each event handler is effectively a little service running in the container. Note ICompositePresentationEventHandler is a simple role interface that allows us to register them all at once in the IoC container:

public interface ICompositePresentationEventHandler {}...container.AddFacility<StartableFacility>();// Register event handlers in containercontainer.Register(    AllTypes        .Of<ICompositePresentationEventHandler>()        .FromAssembly(Assembly.GetExecutingAssembly()));