CRM 2015 Plugins – Avoiding Infinite Loops

This has been a pain for quite some time and have been using (localContext.PluginExecutionContext.Depth > 1) to avoid the infinite plugin loop. BUT this also creates another problem when the plugin suppose to execute either during data import or when using a workflow to create/update.

Problem SOLVED by using localContext.SharedVariables in the plugin. First you need a function to check if the SharedVariables exist before executing your plugin logic, if it does not exist then add it. The trick is to check the SharedVariables in the parent context of the context. See below code:

protected void ExecutePostCaseUpdate(LocalPluginContext localContext)
if (localContext == null)
throw new ArgumentNullException(“localContext”);

if (!CheckRecursionIndicator(localContext.PluginExecutionContext, “ExecutePostCaseUpdateIndicator”)) return;
var updateCase = ((Entity)localContext.PluginExecutionContext.InputParameters[“Target”]).ToEntity();

// TODO: Implement your custom Plug-in business logic.
updateCase.Title = “Plugin Shared Viarable Test”;

/// Check plugin loop recursion

private bool CheckRecursionIndicator(IPluginExecutionContext context, string recursionIndicator)
if (!context.SharedVariables.Contains(recursionIndicator))
while (context.ParentContext != null)
if (context.ParentContext.SharedVariables.Contains(recursionIndicator))
return false;
context = context.ParentContext;

context.SharedVariables.Add(recursionIndicator, (Object)true);
return true;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Workflow Elements by Aiden Kaskela

Microsoft Business Solutions MVP (CRM), Contractor, Evangelist


Real Experiences from Analyzing, Architecting, developing and working with Dynamics CRM, Dynamics 365 and sometimes .net

Mark Margolis's Blog

It's about Software, CRM, Product Development and sometimes Food.


Gareth Tucker on Microsoft Dynamics CRM

Donna Edwards

Sharing my Journey with Microsoft Dynamics 365 Business Solutions

The Blog

The latest news on and the WordPress community.

%d bloggers like this: