Search code examples
servicebusrebus

How to get the source address in Rebus?


How do I get the source address in a message received?

The context is that I'm designing a monitor for a service bus implemented with Rebus. I use the publish - subscribe pattern thus a message is always published on a topic. The monitor subscribes to all topics in order to supervise that a service has send something and so is alive and healthy. Though in a message handler the received message don't contain any source address or information identifying the service publishing. This means it's not possible to supervise which services are alive and healthy. Of course I can create an attribute "Service" identifying the service publishing in all messages. This implies that each service have to set the attribute before publishing a message, which I find a bit cumbersome. The source address is there and can identify the service publishing.


Solution

  • When you're in a Rebus message handler, you can access the IMessageContext - either by having it injected by your IoC container (which is the preferrent way, because of the improved testability), or by accessing the static MessageContext.Current property.

    The message context gives you access to a couple of things, where the headers of the incoming transport message can be used to get the return address of the message (which, by default, is set to the sender's input queue).

    Something like this should do the trick:

    public class SomeHandler : IHandleMessages<SomeMessage>
    {
        readonly IMessageContext _messageContext;
    
        public class SomeHandler(IMessageContext messageContext)
        {
            _messageContext = messageContext;
        }
    
        public async Task Handle(SomeMessage message)
        {
            var headers = _messageContext.TransportMessage.Headers;
            var returnAddress = headers[Headers.ReturnAddress];
    
            // .. have fun with return address here
        }
    }