I couldn’t find a good example on the best way to integrate the RabbitMQ C# client in a .NET core application. So time to write a post about it.
I would recommend to use the Hosted Services, either directly through the IHostedService or through the BackgroundService.
Let’s see how to do it using the BackgroundService:
- We create a new class that inherits from BackgroundService:
- We’ll use the StartAsync method to create the Connectionfactory, Connection and a Channel to listen on:
Remark: Notice the DispatchConsumersAsync = true in the ConnectionFactory configuration. This is important to be able to use an async consumer. If you don’t add this configuration no messages will be picked up by the AsyncEventingBasicConsumer.
- We also implement the StopAsync method to cleanup when our backgroundservice is shutdown:
- Now the only thing left is to create a consumer to start receiving messages. We’ll use the ExecuteAsync method for that:
- Of course we should not forget to register our Hosted Service: