Search code examples
c#.net-corerabbitmqeasynetq

EasyNetQ is not acknowledging received messages


After connecting and receiving messages from RabbitMQ they are not being removed from the queue.

Every time I connect I receive the same messages, and only one.

using(bus = RabbitHutch.CreateBus("host=localhost"))
{
    bus.Receive<MyMessage>("my-queue", message => Console.WriteLine("MyMessage: {0}", message.Text));
}

Solution

  • As detailed in Connecting to RabbitMQ, create a single instance of the Bus and use it in the whole application.

    I have identified the following procedures:

    1. Create an instance of the Bus that is application-wide
    2. Optionally, add it as a Singleton in the dependency injection
    3. Start listening to messages
    4. Register to dispose the Bus once the application shuts down

    This is the simplified Startup.cs with the relevant snippets as demo code:

    public class Startup
    {
    
        // This will be your application instance
        IBus bus;
    
        public void ConfigureServices(IServiceCollection services)
        {  
            // Create, assign the Bus, and add it as Singleton to your application
            bus = RabbitHutch.CreateBus("host=localhost");
            // now you can easyly inject in your components
            services.AddSingleton(bus);
        }
    
        public void Configure(IHostApplicationLifetime lifetime)
        {
            // Start receiving messages from the queue
            bus.Receive<MyMessage>("my-queue", message => Console.WriteLine("MyMessage: {0}", message.Text));
    
            // Hook your custom shutdown the the lifecycle
            lifetime.ApplicationStopping.Register(OnShutdown);
        }
        private void OnShutdown()
        {
            // Dispose the Bus
            bus.Dispose();
        }
    }