Message publishing based programming?
Ever since learned about using event aggregators to publish messages instead of using events I've managed to most events in my code (minus the ones that connect WPF control properties to 开发者_StackOverflow社区my code). The issue now is that it seems I'm really overloading my services with handlers. Cruising around GitHub I can see people implement event aggregators (seems to take on another name such as bus) and create a class to handle each type of message.
For example:
public class SomeHandler : IHandle<SomeMessage>
{
private readonly IEventAggregator _eventAggregator;
public SomeHandler(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
_eventAggregator.Subscribe(this);
}
public void Handle(SomeMessage message)
{
Console.WriteLine("Handled SomeMessage.");
}
}
What's the term used for this type of programming? I'd like to learn more about it.
It is specifically based on the classic Mediator Pattern:
With the mediator pattern, communication between objects is encapsulated with a mediator object. Objects no longer communicate directly with each other, but instead communicate through the mediator. This reduces the dependencies between communicating objects, thereby lowering the coupling.
Your specific code example appears to be using Caliburn Micro's EventAggregator. Many current implementations of the Mediator Pattern are referred to as "Event Aggregators", and are common components in MVVM Pattern libraries. It's a messaging pattern.
In terms of messaging patterns, the following book should be of interest:
Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions
Although it is more about using messaging for systems integration, than using messaging to decouple components within an application.
I would rather call it pub/subscribe.
A bit more modern approach is to use an inversion of control container to get all subscribers of a message.
var subscribers = _container.ResolveAll<ISubscriberOf<IMyMessage>>();
foreach (var subscriber in subscribers)
{
subscriber.Handle(myMessage);
}
You can also google "event driven architecture" to find more interesting implementations
精彩评论