Thursday, November 10, 2011

context.Depth in Plugin

All,

I was facing a weird issue, when updating an entity from another entity. Let me be more clear in what I mean with an example as explained below.

Example:

  • I had registered a Plugin on Entity A


  • I had another plugin registered on Entity B


  • To meet one of the Business scenario, I was doing an Update from the Entity B on Entity A


  • There was also a workflow which was running on Entity B


  • The Issue was when updating Entity B, the execution context in Entity A was getting in to an infilite loop and was throwing up an exception.

    Inorder to overcome the above scenario, we need to make use of the context.Depth property.

    Here is how it works:
    1) The value of context.Depth property == 1 (when the plugin was initiated from an Entity A [where the plugin was registered])
    2) The value of context.Depth property == 2 (when the plugin was initiated from an Entity B and the value of Depth is 2 in the execution context of Entity A, when the update happening from an Entity B.
    3) The value of context.Depth property == 3 when the Plugin context enters Entity A from a workflow.

    To overcome the above scenario's, fallowing is the code that you need to add it in your Plugin execute method.
    if (context.Depth > 1)
     {
        return; 
     }
    

    Hope this helps,
    Chaitanya...

    4 comments:

    Anonymous said...

    Interesting.. Nice to know these concept. solved my problem.
    Thank you.

    Anonymous said...

    Good idea. But what about thread-safety? See: http://social.microsoft.com/Forums/en-US/061836a1-a507-4f44-987d-64d0d74074db/dynamics-crm-2011-plugin-thread-safety

    It won't work reliable.

    Chetan Shetty said...

    Can you explain depth=3 in details in your scenario.

    sybaris said...

    Thanks for your explain.
    Is there is a way in a plug-in, when depth==2 to know who is the caller (at depth==1) ?