Using Global Variables in a CRM 2011 Plug-In

Visit Website View Our Posts

The CRM 2011 SDK states the following:

Note For improved performance, Microsoft Dynamics CRM caches plug-in instances. The plug-in's Execute method should be written to be stateless because the constructor is not called for every invocation of the plug-in. In addition, multiple threads could be running the plug-in at the same time. All per invocation state information is stored in the context. This means that you should not use global class variables in plug-ins.
This is easy to prove. In your plug-in code, simply add a global variable named recordCounter and set it to zero. When the plug-in executes, have it call a method that loops 10 times and in each iteration, increments the recordCounter by 1. When you are done, the value will be 10. Now execute the plugin again, and this time the value will be 20 and not 10. Even though the plug-n may have been executed by a different user, on a different day, by a different trigger, the value will be 20 and not the desired 10.
Pull your logic out to a class so that there are no variables in the plug-in, but call the method in the class from the plugin, and you will get the same result. This can be frustrating when you have multiple methods running, one after the other, and each one affects one or more values that you need to keep track of but do not want to keep returning because you might want to return something more crucial to the actual process. For example, a method that returns a bool, but you want to know how many records it processed before failing, what the exception was, etc.


It seems you can get around this when you have to use global variables by not using a static class with static members. Use a regular class and instantiate it before calling a method and your global variable values inside your class seem to get contained within the context of the instantiation. I cannot confirm this to be 100% accurate but in all the testing that I did, the results were always the same and the values did not get overwritten by other process using the same class.

Wishing for more great blog posts by Rockton Software? Check them out

Written By Gary Rasmussen, Developer at Rockton Software.

Show Buttons
Hide Buttons