Some days ago, when I was working with PRISM, I needed to send some notifications from one view to another based on some business logic. This is something like, if a view receives a notification from other resources, the view requires changing its appearance. To handle this type of situation, we usually remove the view, update its properties, and add the view in the particular region again. Another way we do it is by using the .NET Framework Events mechanism but this is not loosely coupled.
In PRISM, there is a nice way to do that especially to communicate with different Views/Modules (User controls, Entities, external project resources, and so forth) by using the EventAggregator
service.
The EventAggregator
service is primarily a container for events that allow decoupling of originators and receivers so that they can develop autonomously.
I share with you here some of my code in which I have used the EventAggregator
service.
This is the entity class:
public class Company
{
public Company()
{ }
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Postcode { get; set; }
public Country Country{ get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
}
The event that I have used has been given below. The publisher and subscriber will use this event to communicate with themselves:
public class CompanyAddedEvent:CompositePresentationEvent<Company>
{
}
The MyEventAggregator
class is basically for the EventAggregator
instance:
public class MyEventAggregator
{
private static EventAggregator myEventAggregator = null;
private static readonly object syncLock = new object();
private MyEventAggregator() { }
public static EventAggregator GetEventAggregator()
{
lock (syncLock)
{
if (myEventAggregator == null)
{
myEventAggregator = new EventAggregator();
}
return myEventAggregator;
}
}
}
Event publishing:
MyEventAggregator.GetEventAggregator().GetEvent<CompanyAddedEvent>().Publish(your company Object);
Event subscription:
MyEventAggregator.GetEventAggregator().GetEvent<CompanyAddedEvent>().Subscribe((company) =>
{
}, false);
One thing I need to add here is, the publisher and subscriber do not have a direct reference to each other. That is, multiple publishers can raise the same event and multiple subscribers can listen to the same event.
This way, the event may subscribe by different views/modules and, once the event is published, the subscriber will get the notification and can start the task accordingly. This is very easy stuff and by using this facility, you could do very nice things. However, if you want to know the details, please have a look at this article.