我正试图用.NET Core 3.1和Rebus执行一次优雅的关闭,但当我试图将Rebus注入IHostedService时,它会停止记录信息。
我的设置如下
internal class LifetimeEventsHostedService : IHostedService
{
private readonly ILoggingAdapter<LifetimeEventsHostedService> _logger;
private readonly IHostApplicationLifetime _appLifetime;
private readonly IBus _bus;
public LifetimeEventsHostedService(
ILoggingAdapter<LifetimeEventsHostedService> logger,
IHostApplicationLifetime appLifetime,
IBus bus)
{
_logger = logger;
_appLifetime = appLifetime;
_bus = bus;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_appLifetime.ApplicationStarted.Register(OnStarted);
_appLifetime.ApplicationStopping.Register(OnStopping);
_appLifetime.ApplicationStopped.Register(OnStopped);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
private void OnStarted()
{
_logger.LogWarning(new LogItem { Message = "Application Started." });
}
private void OnStopping()
{
_logger.LogInformation(new LogItem { Message = "Application Stopping." });
_bus.Advanced.Workers.SetNumberOfWorkers(0);
}
private void OnStopped()
{
_logger.LogInformation(new LogItem { Message = "Application Stopped." });
}
}
然后在我的创业公司,我有
services.AddHostedService<LifetimeEventsHostedService>();
当您使用任何Rebus的IoC集成包(Rebus.ServiceProvider、Rebus.CastleWindsor、Rebus.Autofac等(时,它会自动设置自己,以便在处理容器时正常关闭。
因此,如果您希望总线正常关闭,只需确保在应用程序关闭时,它所在的IoC容器得到处理即可。
这也适用于内置的容器适配器(它实际上不是IoC容器,更像是某种处理程序工厂(——只需执行以下操作(或等效操作(:
using (var activator = new BuiltinHandlerActivator())
{
Configure.With(activator)
.Transport(...)
.(...)
.Start();
// bus is running now
}
// bus is stopped – all handlers have finished executing
然后总线将优雅地关闭,停止接收操作,给所有处理程序最多60秒的时间(如果我没记错的话(来完成他们正在做的任何事情。