我正在 asp.net core 中创建控制台应用程序,该应用程序将在不同的环境中作为后台服务运行。我使用了“ Microsoft.Extensions.Hosting ”提供的“ BackgroundService ”类。我想在程序启动时运行其“ ExecuteAsync ”方法。
文件:程序.cs
public static void Main(string[] args)
{
var host = new HostBuilder()
.ConfigureHostConfiguration(configHost =>
{
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<IHostedService,RabbitLister>();
})
.UseConsoleLifetime()
.Build();
}
Run Code Online (Sandbox Code Playgroud)
文件:RabbitLister.cs
public class RabbitLister : BackgroundService
{
private readonly IEventBus _eventBus;
private readonly ILogger<RabbitLister> _logger;
public RabbitLister()
{
}
public RabbitLister(IEventBus eventBus, ILogger<RabbitLister> logger)
{
_eventBus = eventBus;
_logger = logger;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
_eventBus.SubscribeDynamic("myQueue");
return Task.CompletedTask;
}
}
Run Code Online (Sandbox Code Playgroud)