We have an endpoint that handles several types of messages (commands).
The processes sending the commands sometimes need to have a combination of these commands executed in a particular order and in a single database transaction (for data consistency reasons). If any of the commands fail, the transaction will be rolled back and subsequent commands aborted.
Rather than create a separate command for every unique combination of commands that need to be executed in a single transaction, I want to create a more general solution to the problem that allows for any combination of commands.
I’ve been reading the documentation on Unit of Work but I can’t see examples of the scenario I describe - how would you know when to start and end the transaction if the messages are separate?
I’m currently considering creating a special ‘composite’ command message, which contains a polymorphic list of inner commands. The message handler for the composite command would create the transaction, then forward the inner messages to the relevant message handlers (in order, and with the database transaction), and finally commit the transaction.
I have two questions about this:
- Am I correct in assuming the NSB Unit of Work does not solve this problem? If not, how would you use it to solve this problem?
- Assuming a composite command is the correct approach, should I ‘send to self’ the inner commands, or should I directly call the message handlers?
In case it affects the answer, here are the details of our set-up:
- NServiceBus 6
- MSMQ transport (no DTC)
- SQL Server persistence
- Single process for handling the commands (running on a Windows cluster for availability)
- SQL Server database being updated as part of the message handling