Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }
    }
}
like image 513
OriginalUtter Avatar asked Dec 11 '22 07:12

OriginalUtter


1 Answers

The accepted answer clears up the subscription side:

cfg.SubscriptionEndpoint(
    host,
    "sub-1",
    "my-topic-1",
    e =>
    {
        e.ConfigureConsumer<TestConsumer>(provider);
    });

For those wondering how to get the bus configuration right on the publish side, it should look like:

cfg.Message<TestMessage>(x =>
{
    x.SetEntityName("my-topic-1");
});

You can then call publish on the bus:

await bus.Publish<TestMessage>(message);

Thanks to @ChrisPatterson for pointing this out to me!

like image 80
Simon Ness Avatar answered Jan 22 '23 07:01

Simon Ness