Skip to content

Events as interfaces

elliotritchie edited this page Nov 18, 2012 · 3 revisions

NServiceBus recommends the use of interfaces for events. This allows you to take advantage of message inheritance with NServiceBus.

For example an AddressChangedEvent represents 'what' has changed within a system. The events 'AddressCorrectionEvent' and 'CustomerMovedEvent' represent 'why' something changed within a system and could both inherit from AddressChangedEvent. Any event handlers within the system now have a choice as to which event they want to handle. If the handler is only interested in persisting data to a database, then it could just listen for AddressChangedEvent. If on the other hand the event handler should trigger the sending of a letter welcoming the customer to their new home, then it would listen for the more specific CustomerMovedEvent.

So why can't you do this with classes? Unfortunately NServiceBus doesn't allow for class inheritance hierarchies and will ignore them. Fortunately though using interfaces for events means you can also take advantage of multiple inheritance, helping you to eliminate downtime of your application by providing you with a maintainable message versioning strategy.

Here's how you can use interfaces for events with NES:

public class Customer : AggregateBase
{
    public void Move(string street, string city, string county, string postcode)
    {
        Apply<CustomerMovedEvent>(e =>
        {
            e.CustomerId = Id;
            e.Street = street;
            e.City = city;
            e.County = county;
            e.Postcode = postcode;
        });
    }
}
Clone this wiki locally