Консольное приложение .NET 6, использование RabbitMQ не работает, если оно находится вне файла Program.csC#

Место общения программистов C#
Ответить
Anonymous
 Консольное приложение .NET 6, использование RabbitMQ не работает, если оно находится вне файла Program.cs

Сообщение Anonymous »


I'm trying to create a consumer on console application app according to this example:
https://rabbitmq-website.pages.dev/tuto ... 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.


Источник: https://stackoverflow.com/questions/780 ... out-of-the
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»