Liana
Liana

Reputation: 45

MassTransit: should I stop the bus after publishing or leave it?

I was stuck here with a problem. I am using the publish topology of MassTransit, and I did NOT start the bus after configuring it because I saw from somewhere(forgot it, sorry) saying that the bus could publish messages without starting it.

It worked fine publishing messages. So I want to ask, should I stop the bus after publishing under the condition that I did not start it?

And if yes, what would be the benefits of stopping it rather than leaving it?

Here is my Publisher class:

public class MessagePublisher<TMessage> : IPublisher<TMessage> where TMessage : class
    {
        private readonly  IBusControl _busConsControl;

        public MessagePublisher(BusConfigurationDto config)
        {
            _busConsControl = config.CreateBus();
        }

        public async Task PublishMessageAsync(TMessage message)
        {
            await _busConsControl.Publish(message);
        }
}

And BusConfigurationDto Class:

public class BusConfigurationDto
    {
        public string Host { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string ExchangeName { get; set; }
        public string QueueName { get; set; }

        public IBusControl CreateBus()
        {
            IBusControl bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                IRabbitMqHost host = cfg.Host(new Uri(Host), hostConfigurator =>
                {
                    hostConfigurator.Username(UserName);
                    hostConfigurator.Password(Password);
                });

                cfg.ReceiveEndpoint(host, QueueName, ep =>
                {
                    ep.Bind(ExchangeName, s => { s.Durable = true; });
                });
            });

            return bus;
        }
    }

Appreciate if someone proficient could help, many thanks!

Upvotes: 0

Views: 843

Answers (1)

Chris Patterson
Chris Patterson

Reputation: 33268

You should Start the bus at application startup, and Stop it when your application exits. Otherwise, you won't know if the configuration is right, and if RabbitMQ is available, until sometime much later when your publisher attempts to publish a message. It's also expensive to start/stop the bus every time you publish a message, which is why keeping it up and running is recommended.

Upvotes: 1

Related Questions