Skip to content

Instantly share code, notes, and snippets.

@dariogriffo
Last active March 5, 2019 10:01
Show Gist options
  • Save dariogriffo/a96ba2c55c6660c5d500317692282d19 to your computer and use it in GitHub Desktop.
Save dariogriffo/a96ba2c55c6660c5d500317692282d19 to your computer and use it in GitHub Desktop.
namespace ConsoleApp7
{
using System.Threading;
using System.Threading.Tasks;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Rebus.Bus;
using Rebus.Config;
public class Message
{
}
public class WindowsService : IHostedService
{
private readonly IBus _bus;
private readonly CancellationTokenSource _cancellationTokenSource;
public WindowsService(IBus bus, CancellationTokenSource cancellationTokenSource)
{
_bus = bus;
_cancellationTokenSource = cancellationTokenSource;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await _bus.Subscribe<Message>();
}
public Task StopAsync(CancellationToken cancellationToken)
{
_cancellationTokenSource.Cancel(); // This will set internal rebus token to cancelled
return Task.CompletedTask;
}
}
class Program
{
static async Task Main(string[] args)
{
var cancellationTokenSource = new CancellationTokenSource();
var hostBuilder = new HostBuilder()
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>((context, builder) =>
{
builder.RegisterInstance(cancellationTokenSource).AsSelf();
builder
.RegisterRebus((configurer, c) => configurer.Transport(t => t.UseRabbitMq("connString", "inputQueue")));
/**
* Ideally here do something like
* RegisterCancellationTokenSource(cancellationTokenSource)
*/
});
await hostBuilder.RunConsoleAsync(cancellationTokenSource.Token);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment