'RabbitMQ Sample not working in WPF

I'm trying to use rabbitMQ under a WPF application.I've followed the sample that are present on rabbitmq site.

The sender is a console application that does

   static void Main(string[] args)
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };


        using (var connection = factory.CreateConnection())
        {

                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "hello",
                        durable: false,
                        exclusive: false,
                        autoDelete: false,
                        arguments: null);

                    string message = "Hello World!";
                    var body = Encoding.UTF8.GetBytes(message);

                    channel.BasicPublish(exchange: "",
                        routingKey: "hello",
                        basicProperties: null,
                        body: body);
                    Console.WriteLine(" [x] Sent {0}", message);
                }
            }

    }

The MainWindowViewModel does

 public class MainWindowViewModel :ViewModelBase
{
    protected override Task InitializeAsync()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using (var connection = factory.CreateConnection())
        using (var channel = connection.CreateModel())
        {
            channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);

            var consumer = new EventingBasicConsumer(channel);
            consumer.Registered += Consumer_Registered;
            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine(" [x] Received {0}", message);
            };
            channel.BasicConsume(queue: "hello", autoAck: true, consumer: consumer);

        }

        return base.InitializeAsync();
    }

    private void Consumer_Registered(object sender, ConsumerEventArgs e)
    {
        int t = 0;
    }
}

This code doesn't work on wpf. the same put in a console application works

I've noticed that the Consumer_Registered is fired... anyone has got a similar issue? As far I've seen the channel creation is ok

Thanks



Solution 1:[1]

The connection and the channel dispose when function InitializeAsync is finished. You should keep them alive. One option is to add them as properties, and assign them in InitializeAsync.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tzvi Merling