A RabbitMQ client for ASP .NET Core 6 with instrumentation so that events are properly correlated in Application Insights.
Explore the InstrumentedRabbitMqDotNetClient.TestApplication
to understand how to use it. It showcases this sequence:
PublishEventController
=> Publishes TestEvent
=> TestSubscription
receives it and publishes TestEvent2
=> Test2Subscription
receives it.
- In the
Startup
class, add:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Other initialization logc
services.AddRabbitMQSubscriberHostedService("name-of-the-queue");
}
}
- Declare a
record
that inherits fromIEvent
.
public record MyEvent : IEvent
{
public string EventName => "my.event";
}
- Inject
IEventPublisher
in a class:
public class MyClass
{
private readonly IEventPublisher _eventPublisher;
public MyClass(IEventPublisher eventPublisher)
{
_eventPublisher = eventPublisher;
}
public void DoSomething()
{
this._eventPublisher.Publish(new MyEvent())
}
}
- Create a class to inherit from
IEventSubscription<MyEvent>
:
public class MyEventSubscription : IEventSubscription<MyEvent>
{
public Task HandleEventAsync(MyEvent receivedEvent, string operationId)
{
// Your logic here.
}
}
The aporoach is to emualte Azure Service Bus, so that Application Insights shows the nested messages and adds some information about the queue as shown in the image above.
But you do not have to do anything besides configure the Application Insights connection string.
A DiagnosticSource is available in the Instrumentation
folder (It is a simplification of the ServiceBusDiagnosticSource).
The EventPublisher
uses it to start the activity.
The RabbitMQSubscriberHostedService
uses it to start processing the event and to to signal that the event processing has finished.
- Create an Azure Application Insights.
- Copy the connection string.
- Set it in the env var
APPLICATIONINSIGHTS_CONNECTION_STRING
. When debugging, it is in thelaunchSettings.json
file in th Properties folder of the TestApplication.