As you will likely have noted, the SDK for CRM 2011 (as for CRM 4.0) states:
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.
I understand, of course, the reason for not having volatile variables declared in the plug-in due to not being thread-safe and the constructor not always being called, however what about constants? Surely there can be no risk posed in such a scenario, since, as long as the value is present, it isn't being changed? Alternatively, what about global-scope variables that require a(n expensive) query to populate them and therefore it might be desireable to purposely cache those values between plug-in calls - particularly again assuming that the values are universal for all users.
As an example, suppose I use a custom system settings entity in CRM. I could use a global class variable which stores the value of these settings. At the point in my plug-in when I need to use a setting, I could check if my variable is null. If it is, I run a routine to fetch the values, if not, I use the values already stored.
Can anyone comment on whether I am missing something here? Microsoft's statement feels (to me at least) too broad-brush. Perhaps this is for simplicity and unambiguity, but despite violating this "rule" I have not experienced any negative side effects when using the aforementioned approach so far. Of course, I may well be missing something...
Example:
public class MyPlugin : IPlugin
{
private static string _mySystemSetting;
public void Execute(IServiceProvider serviceProvider)
{
if(_mySystemSetting == null){
_mySystemSetting = GetSystemSetting("MySetting);
}
...
}
private string GetSystemSetting(string settingName)
{
...
}
}