Search code examples
c#.netrabbitmq

.NET 6 Console Application, RabbitMQ consuming doesn't work when it's out of the Program.cs file


I'm trying to create a consumer on console application app according to this example:
https://rabbitmq-website.pages.dev/tutorials/tutorial-six-dotnet

I notice that when I shift the code outside the program.cs file to different class, it's not working, The code is exactly the same

The code in my program.cs file

var factory = new ConnectionFactory { HostName = "localhost" };
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();

channel.QueueDeclare(queue: "rpc_queue",
                     durable: false,
                     exclusive: false,
                     autoDelete: false,
                     arguments: null);
channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
var consumer = new EventingBasicConsumer(channel);
channel.BasicConsume(queue: "rpc_queue",
                     autoAck: false,
                     consumer: consumer);

consumer.Received += (model, ea) =>
{
    string response = string.Empty;

    var body = ea.Body.ToArray();
    var props = ea.BasicProperties;
    var replyProps = channel.CreateBasicProperties();
    replyProps.CorrelationId = props.CorrelationId;

    try
    {
        var message = Encoding.UTF8.GetString(body);
        Console.WriteLine($"Consumer: message from clien => {message}");
        response = "This message is from Consumer";
    }
    catch (Exception ex)
    {
        response = string.Empty;
    }
    finally
    {
        var responseBytes = Encoding.UTF8.GetBytes(response);
        channel.BasicPublish(exchange: string.Empty,
                             routingKey: props.ReplyTo,
                             basicProperties: replyProps,
                             body: responseBytes);
        channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
    }
};
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();

And the code in some other class is exactly the same

public class RcpServer
{
 public void Start()
 {
  [Same code as above without the 2 last lines (Console.read/Console.write)]
 }
}

Then in program.cs file I have the following code

RcpServer rcpServer = new RcpServer();
rcpServer.Start();
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();

But this code doens't work,

After some searching I found this post RABBITMQ C# Works nice on console but not for a service but unfortunately couldn't solved it :(

What I need is to run the consumer as "background" service.
Please help,
Thanks in advance.


Solution

  • You can use .net worker service to consume messages see