Publish and Handle an Event

Component: NServiceBus
NuGet Package NServiceBus (5.x)
Standard support for version 5.x of NServiceBus has expired. For more information see our Support Policy.

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>
{
    IBus bus;

    public CreateUserHandler(IBus bus)
    {
        this.bus = bus;
    }

    public void Handle(CreateUserCommand message)
    {
        var userCreatedEvent = new UserCreatedEvent
        {
            Name = message.Name
        };
        bus.Publish(userCreatedEvent);
    }
}
  • from a saga handler, when processing another message.
public class CreateUserSaga :
    Saga<CreateUserSaga.SagaData>,
    IHandleMessages<CreateUserCommand>
{
    IBus bus;

    public CreateUserSaga(IBus bus)
    {
        this.bus = bus;
    }

    public void Handle(CreateUserCommand message)
    {
        var userCreatedEvent = new UserCreatedEvent
        {
            Name = message.Name
        };
        bus.Publish(userCreatedEvent);
    }
  • at endpoint startup
using (var bus = Bus.Create(busConfiguration).Start())
{
    bus.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

  • Publish/Subscribe
    Publish/Subscribe, fault-tolerant messaging, and durable subscriptions.

Related Articles


Last modified