I have an ASP.NET Core application where I would like to consume RabbitMQ messages.
I have successfully set up the publishers and consumers in command line applications, but I'm not sure how to set it up properly in a web application.
I was thinking of initializing it in Startup.cs
, but of course it dies once startup is complete.
How to initialize the consumer in a the right way from a web app?
In this article, we are going to take a look at using a message broker, RabbitMQ, with an ASP.NET Core Web API application. Message brokers are applications that allow other applications to send and receive messages in an asynchronous manner.
Registering a Consumer (Subscribing, "Push API") Applications can subscribe to have RabbitMQ push enqueued messages (deliveries) to them. This is done by registering a consumer (subscription) on a queue. After a subscription is in place, RabbitMQ will begin delivering messages.
MassTransit is a . NET Friendly abstraction over message-broker technologies like RabbitMQ. It makes it easier to work with RabbitMQ by providing a lots of dev-friendly configurations. It essentially helps developers to route messages over Messaging Service Buses, with native support for RabbitMQ.
Use the Singleton pattern for a consumer/listener to preserve it while the application is running. Use the IApplicationLifetime
interface to start/stop the consumer on the application start/stop.
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSingleton<RabbitListener>(); } public void Configure(IApplicationBuilder app) { app.UseRabbitListener(); } } public static class ApplicationBuilderExtentions { //the simplest way to store a single long-living object, just for example. private static RabbitListener _listener { get; set; } public static IApplicationBuilder UseRabbitListener(this IApplicationBuilder app) { _listener = app.ApplicationServices.GetService<RabbitListener>(); var lifetime = app.ApplicationServices.GetService<IApplicationLifetime>(); lifetime.ApplicationStarted.Register(OnStarted); //press Ctrl+C to reproduce if your app runs in Kestrel as a console app lifetime.ApplicationStopping.Register(OnStopping); return app; } private static void OnStarted() { _listener.Register(); } private static void OnStopping() { _listener.Deregister(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With