Getting Started
Architecture
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

Publish and Handle an Event

Component: NServiceBus
NuGet Package: NServiceBus (8.1)

Event messages need to either implement IEvent or match a custom DefiningEventsAs convention. See the message design documentation for more details.

Handling an event

In order to handle an event, implement the IHandleMessages<T> interface in any handler or saga class, where T is the specific event type.

Publishing an event

Call the Publish method to publish an event.

There are a few common scenarios for publishing events. Events might be published:

  • from a handler, when processing another message.
public class CreateUserHandler :
    IHandleMessages<CreateUserCommand>
{
    public Task Handle(CreateUserCommand message, IMessageHandlerContext context)
    {
        var userCreatedEvent = new UserCreatedEvent
        {
            Name = message.Name
        };
        return context.Publish(userCreatedEvent);
    }
}
  • from a saga handler, when processing another message.
public class CreateUserSaga :
    Saga<CreateUserSaga.SagaData>,
    IHandleMessages<CreateUserCommand>
{
    public Task Handle(CreateUserCommand message, IMessageHandlerContext context)
    {
        var userCreatedEvent = new UserCreatedEvent
        {
            Name = message.Name
        };
        return context.Publish(userCreatedEvent);
    }
  • at endpoint startup
// Other config
var endpointInstance = await Endpoint.Start(endpointConfiguration);
await endpointInstance.Publish(new MyEvent());

Composing events

In order to support advanced composition scenarios, events can be defined as interfaces. See the Messages as Interfaces for more details.

Samples

Related Articles


Last modified