在 .Net 核心控制台应用程序中触发后台服务 ExecuteAsync 方法
Trigger background service ExecuteAsync method in .Net core console application
我正在 asp.net 核心中创建控制台应用程序,它将 运行 作为不同环境中的后台服务。我使用了“Microsoft.Extensions.Hosting”提供的“BackgroundService”class。当我的程序启动时,我想 运行 它的“ExecuteAsync”方法。
文件:Program.cs
public static void Main(string[] args)
{
var host = new HostBuilder()
.ConfigureHostConfiguration(configHost =>
{
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<IHostedService,RabbitLister>();
})
.UseConsoleLifetime()
.Build();
}
文件: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;
}
}
主机构建完成后,调用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();
}
这将启动托管服务并最终调用执行函数
我正在 asp.net 核心中创建控制台应用程序,它将 运行 作为不同环境中的后台服务。我使用了“Microsoft.Extensions.Hosting”提供的“BackgroundService”class。当我的程序启动时,我想 运行 它的“ExecuteAsync”方法。
文件:Program.cs
public static void Main(string[] args)
{
var host = new HostBuilder()
.ConfigureHostConfiguration(configHost =>
{
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<IHostedService,RabbitLister>();
})
.UseConsoleLifetime()
.Build();
}
文件: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;
}
}
主机构建完成后,调用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();
}
这将启动托管服务并最终调用执行函数