Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?
like image 628
Larry Avatar asked Feb 12 '18 07:02

Larry


1 Answers

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());
    }
}
like image 80
aleha Avatar answered Oct 21 '22 00:10

aleha