title | summary | tags | related | redirects | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Messages, Events and Commands |
What are Messages, Events and Commands and how to define them. |
|
|
|
A Message is the unit of communication for NServiceBus. There are two sub-types of messages that capture more of the intent and help NServiceBus enforce messaging best practices. This enforcement is enabled by default unless disabled in configuration.
Used to request that an action should be taken. A Command is intended to be sent to a receiver (all commands should have one logical owner and should be sent to the endpoint responsible for processing). As such, commands ...
- are not allowed to be published.
- cannot be subscribed to or unsubscribed from.
- cannot implement
IEvent
.
Used to communicate that some action has taken place. An Event should be published. An event ...
- can be subscribed to and unsubscribed from.
- cannot be sent using
Bus.Send()
(since all events should be published). - cannot implement
ICommand
. - cannot be sent using the gateway, i.e.,
bus.SendToSites()
.
Note: For reply messages in a request and response pattern, you may want to use IMessage
since these replies are neither a Command nor an Event.
There are checks in place to ensure following of the best practices. While violating above rules the following exceptions can be seen:
- "Pub/Sub is not supported for Commands. They should be be sent direct to their logical owner." - this exception is being thrown when attempting to publish a Command or subscribe to/unsubscribe from a Command.
- "Events can have multiple recipient so they should be published." - this exception will occur when attempting to use 'Bus.Send()' to send an event.
- "Reply is neither supported for Commands nor Events. Commands should be sent to their logical owner using bus.Send and bus. Events should be Published with bus.Publish." - this exception is thrown when attempting to reply with a Command or an Event.
Note: In Version 3 and Version 4 there are 2 additional messages that can be seen:
- "Reply is not supported for Commands. Commands should be sent to their logical owner using bus.Send and bus." - this exception is thrown when one use reply with a Command.
- "Reply is not supported for Events. Events should be Published with bus.Publish." - this exception will occur when one tries to use reply with an Event.
Messages can be defined via marker interfaces or via conventions.
The simplest way to define a message is to use marker interfaces.
NServiceBus.IMessage
for defining a Message.NServiceBus.ICommand
for defining a Command.NServiceBus.IEvent
for defining an Event.
public class MyMessage : IMessage { }
public class MyCommand : ICommand { }
public class MyEvent : IEvent { }
public interface MyEvent : IEvent { }