Getting Started
Architecture
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

Interfaces as messages

Component: NServiceBus
NuGet Package: NServiceBus (9.1)

Events can be created on the fly from interfaces without first defining an explicit class implementing the interfaces. This technique can be used to support multiple inheritance for polymorphic routing scenarios. In general, it is recommended to use dedicated, simple types as messages instead.

Sending interface messages

Interface messages can be sent using the following syntax:

await endpoint.Send<IMyMessage>(message =>
{
    message.SomeProperty = "Hello world";
});

Replies are supported via:

return context.Reply<IMyReply>(message =>
{
    message.SomeProperty = "Hello world";
});

Publishing interface messages

Interface messages can be published using the following syntax:

return context.Publish<IMyEvent>(message =>
{
    message.SomeProperty = "Hello world";
});

Creating interface messages with IMessageCreator

If an interface message is needed before calling Send or Publish, use IMessageCreator directly to create the message instance:

//IMessageCreator is available via dependency injection
async Task PublishEvent(IMessageCreator messageCreator)
{
    var eventMessage = messageCreator.CreateInstance<IMyEvent>(message =>
    {
        message.SomeProperty = "Hello world";
    });

    await messageSession.Publish(eventMessage);

    //or if on a message handler

    await context.Publish(eventMessage);
}

Related Articles