问题
I am creating console application in asp.net core which is going to run as background service in different environments. I have used "BackgroundService" class provided by "Microsoft.Extensions.Hosting". I want to run its "ExecuteAsync" method when my program gets started.
File: Program.cs
public static void Main(string[] args)
{
var host = new HostBuilder()
.ConfigureHostConfiguration(configHost =>
{
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<IHostedService,RabbitLister>();
})
.UseConsoleLifetime()
.Build();
}
File: 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;
}
}
回答1:
After the host has been build, invoke host.Run()
public static void Main(string[] args) {
var host = new HostBuilder()
.ConfigureHostConfiguration(configHost => {
})
.ConfigureServices((hostContext, services) => {
services.AddHostedService<IHostedService, RabbitLister>();
})
.UseConsoleLifetime()
.Build();
//run the host
host.Run();
}
that will start hosted service and eventually call the execute function
来源:https://stackoverflow.com/questions/56903147/trigger-background-service-executeasync-method-in-net-core-console-application