我正在尝试使用.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>();
答案 0 :(得分:1)
使用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秒(如果我没有记错的话)完成他们的工作。