Search code examples
nservicebusnservicebus4

Call OutgoingHeaders using NServiceBus.Host


Using NServiceBus 4.0.11 I would like to call

Bus.OutgoingHeaders["user"] = "john";

The Header Manipulation sample shows how to call it with a custom host. I would like to call it while using the NServiceBus.Host.

So actually I would like to have a reference to the instance of the Bus, to call OutgoingHeaders on. Tried IWantCustomInitialization but that gives me an exception when calling CreateBus in it. INeedInitialization isn't the way to go neither.

How should I call Bus.OutgoingHeaders["user"] = "john"; while using the NServiceBus.Host?


Solution

  • Reading your question makes me think that you want to add this header to a certain message that you want to send during initialization/startup or when handling a message. Usually, headers have a more generic behavior as they need to be applied to more than one message.

    Instead of setting the header before sending the message you can also add the header via a message mutator or behavior.

    Behavior

    public class OutgoingBehavior : IBehavior<SendPhysicalMessageContext>
    {
        public void Invoke(SendPhysicalMessageContext context, Action next)
        {
            Dictionary<string, string> headers = context.MessageToSend.Headers;
            headers["MyCustomHeader"] = "My custom value";
            next();
        }
    }
    

    Mutator

    public class MutateOutgoingTransportMessages : IMutateOutgoingTransportMessages
    {
        public void MutateOutgoing(object[] messages, TransportMessage transportMessage)
        {
            Dictionary<string, string> headers = transportMessage.Headers;
            headers["MyCustomHeader"] = "My custom value";
        }
    }
    

    Documentation

    See: http://docs.particular.net/nservicebus/messaging/message-headers#replying-to-a-saga-writing-outgoing-headers for samples.