Configuring Rebus in a .net core Worker Service (or a Console App)

Viewed 1313

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

2 Answers

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 BackgroundService()
    {
        // configure the bus

        services.AddResbus(
            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((hostContext, services) =>
        {
            services.AddHostedService<MyBackgroundService>();
        });

in your startup.

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.

Related