Skip to content
bsommardahl edited this page Jun 20, 2012 · 2 revisions

To use DomainEvents in your domain entities, just add an event field to your domain entity class like this:

public class Account {
    public event DomainEvent NotifyObservers;
}

We called the event “NotifyObservers” simply because that expresses what is happening. You can call the event field whatever you'd like. But, we recommend that you use a word or phrase that expresses a general notification of the subscribers or observers of the domain entity... not the specific behavior (i.e. “NotifyThatNameChanged” is not a good event field name since it's specific to a type of behavior. What happens if your domain entity has other types of behavior?)

Now, to use the new DomainEvent field on your entity, you could do something like this:

public class Account
{
    public Account(string name) {
        Name = name;
    }

    public string Name { get; private set; }
        
    public event DomainEvent NotifyObservers;

    public void ChangeName(string newName) {
        var oldName = Name;
        Name = newName;

        //here, we're going to notify the users that the name changed... 
        NotifyObservers(new TheNameChanged {OldName = oldName, NewName = newName});
        //why even bother with a comment? The code is expressive enough, right?     
    }
}

On the other side of the equation, we have an event dispatcher that is responsible for finding any matching event handlers and “dispatching” them. Here's an example of an event handler that matches our “TheNameChanged” event:

public class LogThatNameChanged : IDomainEventHandler<TheNameChanged>
{
    public void Handle(TheNameChanged @event) {
        Console.WriteLine(string.Format("## (LogThatNameChanged) -- The name '{0}' changed to '{1}'.", @event.OldName, @event.NewName));    
    }
}

This event handler accepts our TheNameChanged event and logs it to the console.

Clone this wiki locally