These slides gives guides you through what the Publish-Subscribe pattern is, how to create an Event Aggregator, how you can use it in the UI and in other layers and 2 code samples that refactors from a non pub-sub architecture to a pub-sub architecture.
Publish & Subscribe to events using an Event Aggregator
1. Publish- and Subscribe to
events using an
Event Aggregator
Lars-Erik Kindblad
Senior Consultant
Blog: kindblad.com
2. Agenda
What is the Publish-Subscribe Pattern?
Message
Publisher
Subscriber
Event Aggregator and how to create one
Code Sample #1 and #2 without and with publish-subscribe
Summary
3. What is the Publish-Subscribe Pattern?
Publish-Subscribe = Pub/Sub
Message/event based pattern
The publisher creates and publishes messages through an event
aggregator (message bus) – but don’t program the messages to be sent
directly to any subscribers
The subscribers define what messages they want to subscribe to
Event Aggregator
Subscriber Subscriber
Publisher
Message
MessageMessage
Subscribe
4. What is a Message?
A simple .NET POCO class with or without properties
5. What is a Publisher?
Any class that wants to create and publish a message
6. What is a Subscriber?
Any class that wants to do something when a specific message or event
occurs
7. What is an Event Aggregator?
A lightweight message bus
Accepts a message and publishes it out to only those who subscribes for it
Can be synchronous or asynchronous
Must have
Publish(message) method
Can have
Subscribe(subscriber) method
Unsubscribe(subscriber) method
29. Open Closed Principle
“Software entities (classes, modules, functions, etc.) should be open for
extension, but closed for modification”
The current implementation breaks this principle
Publish-Subscribe would not break the principle
RegisterCustomer
EmailCustomer SmsCustomer
Event Aggregator
EmailCustomer SmsCustomer
RegisterCustomer
Publish message:
CustomerRegistered
Subscribe to &
handle the
message
Invoke
34. Summary
Publish & Subscribe + Event Aggregator gives:
Code that is loosely coupled
Less complex code that is easier to maintain and unit-test
Where to use it?
1. UI/Presentation layer
2. Other layers when needed
How to use it?
1. Download or create your own event aggregator
2. Define a message
3. Create and publish a message
4. Subscribe to the message