Microsoft Technologies based on the .NET software framework. Miscellaneous topics that do not fit into specific categories.
Hi @Yogi ,
Thanks for reaching out.
In your case, the behavior is related to how the connection and channel are created in AddConsumer(). They are wrapped in using:
using var connection = await factory.CreateConnectionAsync();
using var channel = await connection.CreateChannelAsync();
using disposes the objects when the method finishes. Once AddConsumer() exits, the RabbitMQ connection and channel are closed, so the consumer stops listening. The application keeps running, but there is no active RabbitMQ connection anymore.
When the app restarts, AddConsumer() runs again and creates a new consumer. If there are messages already in the queue, they may be delivered at that time, which can make it appear as if messages are only received after a restart.
In your case, you can still keep everything inside the ASP.NET Core app without using a console app, background service, or MassTransit. The key point is to keep the RabbitMQ connection and channel alive for the lifetime of the application instead of disposing them immediately.
For example, you could keep them as fields in your class:
public class RMQConfig
{
private IConnection _connection;
private IChannel _channel;
public async Task AddConsumer()
{
var factory = new ConnectionFactory { HostName = "localhost" };
_connection = await factory.CreateConnectionAsync();
_channel = await _connection.CreateChannelAsync();
await _channel.QueueDeclareAsync("hello", false, false, false, null);
var consumer = new AsyncEventingBasicConsumer(_channel);
consumer.ReceivedAsync += (model, ea) =>
{
var message = Encoding.UTF8.GetString(ea.Body.ToArray());
Console.WriteLine($"[x] Received {message}");
return Task.CompletedTask;
};
await _channel.BasicConsumeAsync("hello", true, consumer);
}
}
With the connection and channel kept alive, the consumer can continue listening while the ASP.NET Core application is running.
Please treat the code snippet above as a general reference. You may need to adjust the structure to fit your project setup and dependency injection configuration.
For reference, ASP.NET Core typically runs long-lived background tasks through hosted services: https://learn.microsoft.com/aspnet/core/fundamentals/host/hosted-services
Hope this helps! If my answer was helpful, I would greatly appreciate it if you could follow the instructions here so others with the same problem can benefit as well.