rebus-org / Rebus.ServiceProvider

:bus: Microsoft Extensions Dependency Injection container adapter for Rebus
https://mookid.dk/category/rebus
Other
66 stars 32 forks source link

Bus is always disposed before generic host is stopping hosted services #83

Open mksergiy opened 10 months ago

mksergiy commented 10 months ago

Registering bus.Dispose() in IHostApplicationLifetime.ApplicationStopping causes the bus to be disposed before the generic host stops the hosted services

code from RebusInitializer:

// stopping the bus here will ensure that we've finished executing all message handlers when the container is disposed
stoppingToken.Register(() =>
{
    logger?.LogDebug("Stopping token signaled - disposing bus instance {busInstance}", bus);
    bus.Dispose();
    logger?.LogInformation("Bus instance {busInstance} successfully disposed", bus);
});

When I commented out the registration mentioned above, everything worked fine, including the order of stopping RebusBackgroundService.

mookid8000 commented 10 months ago

Hmm actually this might call for giving Rebus the ability to wait for currently executing message handlers to finish - this way, the stopping token above could just set the number of workers to 0 (thus preventing that additional messages are fetched), and then block, waiting for currently executing message handlers to finish.

This bus could then be disposed at a later point in time when everything else has shut down.

I'll run a couple of experiments to see if that would be feasible.