Search code examples
transactionsdynamics-crm

Understanding Plugin Transactions in Dynamics CRM


I'd like to understand how transaction are being committed when using plugins.

I understand there are 4 main operations -

  • Pre Validation - outside transaction

  • Pre Operation - inside transaction

  • Post Operation (sync) - inside transaction

  • Post Operation (async) - outside transaction

But what will happen in the following scenario :

  1. Entity A has a step registered in Post Operation (sync) that updates Entity B.

  2. Entity B has a step registered in Post Operation (async)

As I understand these two steps will be executed in the same transaction, even though Entity B's step is registered as async.

Does that mean that if an error occurs in Entity B's async step the entire transaction is rolled back? including changes made by Entity A's sync step?

Also, what if Entity B has a Pre Validation step as well? Will it be skipped when triggered by Entity A's sync step?


Solution

  • When Dataverse receives e.g. an update for a table record, this event passes the plugin pipeline in a number of stages:

    • Pre validation
    • Pre operation
    • Main operation
    • Post operation
    • Async operation

    The Main operation is where the system itself performs its work. For all other stages we can register custom handlers (plugin steps).

    When the pipeline receives an update from the outside world (through UI or API), the Pre validation stage will be outside a database transaction. In general this is the stage where custom code can add validations and even can on-the-fly modify fields on the record passed to the pipeline. When the input is found not valid, custom code can cancel the update by throwing an exception.

    After the Pre validation stage a database transaction is opened and all database operations that subsequently are performed in the Pre operation, Main operation and Post operation stages are part of that transaction. As a consequence, when in the process an exception is thrown, all create, update and delete operations that were done are rolled back.

    When the Post operation stage is completed, the transaction is committed. When async steps are registered, the system will then schedule an Async operation event. This is outside the database transaction and even out-of-process. The async event will be picked up by another service. You can track the processing of async operation events in the asyncoperation table.

    In the various plugin stages custom code can create or update related records in the system. These operations will pass the same plugin pipeline stages and will all be executed within the original database transaction. This means that when a plugin updates a record, a separate plugin pipeline is triggered and the Pre validation stage of that plugin pipeline invocation will be inside the initial database transaction.