Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger background service ExecuteAsync method in .Net core console application

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;
        }
    }
like image 465
TrinTrin Avatar asked Aug 05 '26 07:08

TrinTrin


1 Answers

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

like image 163
Nkosi Avatar answered Aug 07 '26 23:08

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!