Search code examples
c#azureservicebusmasstransitazure-servicebus-topics

How to specify which Azure Service Bus Topic to use with MassTransit


I've tried using MassTransit to publish a message to a topic named events in an Azure Service Bus. I have problems configuring MassTransit to use my predefined topic events, instead it creates a new topic named by the namespace/classname for the message type. So I wonder how to specify which topic to use instead of creating a new one.

This is the code I've tested with:

using System;
using System.Threading.Tasks;
using MassTransit;
using MassTransit.AzureServiceBusTransport;
using Microsoft.ServiceBus;

namespace PublisherNameSpace
{
    public class Publisher
    {
        public static async Task PublishMessage()
        {
            var topic = "events";
            var bus = Bus.Factory.CreateUsingAzureServiceBus(
                cfg =>
                {
                    var azureServiceBusHost = cfg.Host(new Uri("sb://<busname>.servicebus.windows.net"), host =>
                    {
                        host.OperationTimeout = TimeSpan.FromSeconds(5);
                        host.TokenProvider =
                            TokenProvider.CreateSharedAccessSignatureTokenProvider(
                                "RootManageSharedAccessKey",
                                "<key>"
                            );
                    });

                    cfg.ReceiveEndpoint(azureServiceBusHost, topic, e =>
                    {
                        e.Consumer<TestConsumer>();
                    });
                });

            await bus.Publish<TestConsumer>(new TestMessage { TestString = "testing" });
        }
    }

    public class TestConsumer : IConsumer<TestMessage>
    {
        public Task Consume(ConsumeContext<TestMessage> context)
        {
            return Console.Out.WriteAsync("Consuming message");
        }
    }

    public class TestMessage
    {
        public string TestString { get; set; }
    }
}

Solution

  • If you want to consume from a specific topic, create a subscription endpoint instead of a receive endpoint, and specify the topic and subscription name in the configuration.

    The simplest form is shown in the unit tests:

    https://github.com/MassTransit/MassTransit/blob/develop/tests/MassTransit.Azure.ServiceBus.Core.Tests/Subscription_Specs.cs