How do you handle follow-up actions of important things that happened in your code? For instance when a new user registered on your site you need to send him a registration verification link. Are you just adding the necessary pieces of code into your existing code block? What happens if you need to also send an email to the administrator of the website, so he may already setup the necessary roles for the newly registered user? Or you need to automatically create a backorder when stock of a specific product runs out?
An event is the acknowledgement that something important did happen in your system. The name always indicates that something did happen, so it is always in past tense.
The event subscriber/handler
An event subscriber subscribes to a specific event, its execution happens synchronously. Important thing to notice here is that there can be multiple subscribers to the same event, they will be run in any order. Normally they will happen into the same Context/UnitOfwork/Transaction as the event originator. But it is also possible to queue a new message on a MSMQ/Bus in a subscriber.
Now i personally prefer raising these events from where it belongs, more specific in the domain code. Now how could we raise events in an easy way and automatically execute all the needed subscribers? I avoid doing any form of Dependency Injection in my domain, we’ll need some static gateway to something that dispatches the events
This allows me to do the following in my domain code:
Let’s take a closer look at the event dispatcher contract and 3 example implementations
As i hate those pesky NullReferenceExceptions, i made myself a default null object implementation.
Collecting Events for unit test purposes
This implementation can be used to unit test if a specific event has occurred, although one could also use mocked one.
The one that glues everything together
This is a example implementation useable in your application, it uses a subscriber factory underneath (Typed Factory Facility - Castle Windsor).
Registration details for Windsor and application start code
And for instance in your Global.asax after you setup your container: