4

I have seen that Adding rebus in the ASP.NET Core execution pipeline is very neat using Startup.cs. I wonder if there is a same neat way to do the same for Worker service or generally a console app.

Most .net core console apps I have seen are very simple demo applications. Kindly if there is any concrete sample configuration using .net core console application. Regards Amour Rashid

Amour Rashid
  • 290
  • 3
  • 11

2 Answers2

3

One way would be to add Microsoft's Microsoft.Extensions.Hosting package and build your background service as a BackgroundService:

public class MyBackgroundService : BackgroundService
{
    readonly IServiceCollection _services = new ServiceCollection();

    public MyBackgroundService()
    {
        // configure the bus
        
        services.AddRebus(
            configure => configure
                .Transport(t => t.Use(...))
        );
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var provider = _services.BuildServiceProvider();

        // start the bus
        provider.UseRebus();
        
        while (!stoppingToken.IsCancellationRequested)
        {
            await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
        }
    }
}

which you then add by going

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureServices((_, services) =>
        {
            services.AddHostedService<MyBackgroundService>();
        });

in your startup.

R.P.
  • 105
  • 1
  • 4
mookid8000
  • 18,258
  • 2
  • 39
  • 63
1

Thanks Mogens, Another way is to

var host =CreateHostBuilder(args).Build();

host.UseRebus(); host.Run();

Or in ConfigureServices method .... var provider=services.CreateServiceProvider(); provider.UseRebus();

It helped me I could create Worker Services using rebus.

Amour Rashid
  • 290
  • 3
  • 11