Silverback routes messages based on their type by default. You can customize this behavior using several methods:
1. Routing Function
Use ProduceTo with a lambda to determine the destination topic based on the message content or the IOutboundEnvelope<T> (which provides access to headers and metadata).
Kafka Example:
.Produce<MyMessage>(endpoint => endpoint
.ProduceTo(envelope => envelope.Headers.GetValue<int>("x-random") % 2 == 0 ? "my-even" : "my-odd"))
MQTT Example:
.Produce<MyMessage>(endpoint => endpoint
.ProduceTo(envelope => envelope.Headers.GetValue<int>("x-random") % 2 == 0 ? "my/even" : "my/odd"))
2. Format Strings
You can use a format string in ProduceTo where variable parts are generated from the message.
Kafka Example:
.ProduceTo(
"my-{0}",
message => message.Id % 2 == 0 ? new object[] { "even" } : new object[] { "odd" }))
3. Dedicated Resolver Class
For complex logic, implement a resolver class that can be injected via DI.
- For Kafka: Implement
IKafkaProducerEndpointResolver<TMessage>. - For MQTT: Implement
IMqttProducerEndpointResolver<TMessage>.
Register it using .UseEndpointResolver<TResolver>() in your producer configuration.
4. Dynamic Routing
To select the destination at publish time instead of configuration, enable dynamic routing using .ProduceToDynamicTopic() in the configuration, and then set the destination on the envelope during publication.
Kafka:
await _publisher.WrapAndPublishAsync(
new MyMessage { ... },
envelope => envelope.SetKafkaDestinationTopic("my-topic"));
MQTT:
await _publisher.WrapAndPublishAsync(
new MyMessage { ... },
envelope => envelope.SetMqttDestinationTopic("my/topic"));