Trigger background service ExecuteAsync method in .Net core console application

帅比萌擦擦* 提交于 2021-01-24 05:41:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!