C# Transactions and Unique Indexes

I’ve found an issue with inserts to a collection with a unique index constraint within a transaction. This only fails when there are concurrent actions to insert the same unique index. My session is enlisting with System.Transaction.Current.

The problem is when two threads with separate transactions both try to insert a document with the same unique index - the InsertOneAsync method completes and other actions (publishing to the bus) in the TransactionScope are executed.

The MongoDB exception raised by the “losing” thread to insert is only raised at the point of calling the Session’s CommitTransation(), however this is too late for the other participants in the wider transaction - as all operations completed, therefore the transaction is deemed “Commitable” and they happily commit.

I understand the the insert isn’t commited to the collection until the transaction is completed - however I need to be able to ensure that the publish isn’t allowed if the CommitTransaction() fails? I need to get the InsertOneAsync method to error at the point of execution.

Many thanks.