The default mode for managing subscriptions is auto-subscribe. Every time a subscriber endpoint starts, it determines which events it needs to subscribe to and automatically subscribes to them. For more information on how publish and subscribe works, refer to Publish-Subscribe.
Messages matching both of the following criteria will be auto-subscribed at startup:
- Defined as an event either using
IEventor by the
- At least one message handler and/or saga exists for the given event.
When using a transport that doesn't support publish-subscribe natively, if a message handler is defined for an event but no publisher information can be found, the endpoint will log the following error at startup:
AutoSubscribe was unable to subscribe to event '<event-type-full-name>': No publisher address could be found for message type '<event-type-full-name>'.
In NServiceBus version 7.1 and above, specific event types can be excluded from the auto-subscription mechanism using the following API:
var autoSubscribe = endpointConfiguration.AutoSubscribe(); autoSubscribe.DisableFor<EventType>();
Sagas are treated the same as handlers and will cause an endpoint to subscribe to a given event. It is possible to opt-in to the old exclude saga event handling behavior using:
var autoSubscribe = endpointConfiguration.AutoSubscribe(); autoSubscribe.DoNotAutoSubscribeSagas();
In NServiceBus version 6 and above, it is possible to subscribe to messages not defined as events by manually subscribing to the message type.
A subscriber will not unsubscribe when it stops; it will remain registered at the publisher to receive events. The publisher still sends events to the queue of the stopped subscriber. When the subscriber is started, it will consume the messages from its queue. The subscriber will never lose an event.
Automatic subscriptions by the infrastructure can be disabled using the configuration API:
Events can manually be subscribed and unsubscribed to:
await endpoint.Subscribe<MyEvent>() .ConfigureAwait(false); await endpoint.Unsubscribe<MyEvent>() .ConfigureAwait(false);
In NServiceBus version 6 and above,
Unsubscribe are accessible via the
IMessageSession available on the
IEndpointInstance or within a feature startup task.