Search code examples
c#masstransitkestrel-http-serverasp.net-core-mvc-2.0

How to stop a MassTransit bus in an ASP.NET Core server?


I am studying MassTransit and ASP.NET Core, dependancy injection and successfully implemented something that works. I plan to use the Kestrel web server.

So I had to configure my ASP.NET core project this way in the Startup.cs.

public void ConfigureServices(IServiceCollection services) {

    ...

    var bus = Bus.Factory.CreateUsingRabbitMq(sbc => {
        var host = sbc.Host(new Uri(address), h => {
            h.Username("guest");
            h.Password("guest");
        });
    });

    services.AddSingleton<IBus>(bus);
    services.AddScoped<IRequestClient<GetTagRequest, GetTagAnswer>>(x =>
        new MessageRequestClient<GetTagRequest, GetTagAnswer>(x.GetRequiredService<IBus>(), new Uri(address + "/gettagrequest"), timeOut));

    bus.Start(); // <= ok. how is the bus supposed to stop ?

    ...

Although this works fine, no tutorial mentioned anything about setting bus.Stop() in an ASP.NET core project. I read in MassTransit documentation that a running bus could prevent a graceful exit.

  • Is this a major concern for a Kestrel web server? I have read about process recycling and I am afraid a running bus would compromise this.
  • At which place can I place that bus.Stop() in an ASP.NET Core project ?

Solution

  • You can use ApplicationLifetime events. Just make your IBus object class level variable.

    public class Startup
    {
        private IBus _bus;
    
        public void ConfigureServices(IServiceCollection services) {
            /* ... */
    
            _bus = Bus.Factory.CreateUsingRabbitMq ... 
    
            /* ... */
        }
    
        public void Configure(IApplicationLifetime appLifetime)
        {
            appLifetime.ApplicationStarted.Register(() => _bus.Start());
            appLifetime.ApplicationStopping.Register(() => _bus.Stop());
        }
    }