Search code examples
c#nservicebusnservicebus3

Sending Messages From NServiceBus Host


We have an Audit Message Handler and if any exceptions are thrown within this handler we would like it to send a log message to the LogMessageInputQueue which will be handled by another Message Handler.

Is it possible to send a new message from within an NServiceBus host process? The AuditMessageHandler accepts the handlers IBus in its constructor, but when calling

_bus.Send(new LogFatalMessage(ex));

No exception is thrown, but the message does not appear on the LogMessageInputQueue and seems to simply disappear...

All the handlers and Queues are on the same machine.


Solution

  • OK, figured this out all by myself :)

    After the _bus.Send(new LogFatalMessage(ex)) we re-throw the original error, this causes NServiceBus to rollback its transaction and remove the message from the LogMessageInputQueue.

    By wrapping the _bus.Send() in its own transaction, we stop the rolling back of the NServiceBus transaction from removing the LogMessage from the Queue.

    using (var ts = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
        _bus.Send(new LogFatalMessage(ex));
        ts.Complete();
    }