Sunday, February 13, 2011

Silverlight, PRISM, MVVM, MEF – Part 6

In Prism, loosely coupled components in the application communicate with each other using a event aggregation service that the library provides. The event aggregator service uses a publish/subscribe mechanism for communication. The EventAggregator provides multicast publish/subscribe functionality. This means there can be multiple publishers that raise the same event and there can be multiple subscribers listening to the same event as given below.

In prism communication between publishers and subscribers is done by the CompositePresentationEvent class. This class maintains the list of subscribers and handles event dispatching to the subscribers.
The CompositePresentationEvent class is a generic class that requires the payload type to be defined as the generic type. This helps enforce, at compile time, that publishers and subscribers provide the correct methods for successful event connection.
Event creation is done by creating a class that inherits the CompositPresentationEvent class.
public class EmployeeAddedEvent : CompositePresentationEventEmployee> { }

Publishers raise an event by retrieving the event from the EventAggregator and calling the Publish method. To access the EventAggregator, you can use dependency injection by adding a parameter of type IEventAggregator to the class constructor. For e.g.
private void OnAddNewClicked()
{
    AddNewEmployeeAndPassToEmployeeView();
}

private void AddNewEmployeeAndPassToEmployeeView()
{
    Model.Employee employee = new Model.Employee
    {
            Id = Guid.NewGuid(),
            FirstName = "New Employee",
            LastName = "Last Name",
            ChangedDate = DateTime.Now,
            CreatedDate = DateTime.Now,
            DateOfJoining = DateTime.Now
    };
    _eventAggregator.GetEvent<EmployeeAddedEvent>().Publish(employee);
}

Subscribers can enlist with an event using one of the Subscribe method overloads available on the CompositePresentationEvent class. In our sample, you can use the event subscription as
private void SubcribeToEmployeeAddedEvent(IEventAggregator eventAggregator)
{
    EmployeeAddedEvent employeeAddedEvent = eventAggregator.GetEvent<EmployeeAddedEvent>();

    if (_subscriptionToken != null)
        employeeAddedEvent.Unsubscribe(_subscriptionToken);
    _subscriptionToken = employeeAddedEvent.Subscribe(OnEmployeeAddedEvent, ThreadOption.UIThread, false);
}

public void OnEmployeeAddedEvent(Model.Employee employee)
{
    Employees.Add(employee);
}

If your subscriber no longer wants to receive events, you can unsubscribe by using your subscriber's handler or you can unsubscribe by using a subscription token.
The following code example shows how to directly unsubscribe to the handler.
employeeAddedEvent.Unsubscribe(OnEmployeeAddedEvent);

No comments: