System.InvalidOperationException on Dynamics CRM 2011 Plugin & Workflow

Today, I was facing a strange error on one of the custom workflow activity. The workflow when run in production environment was going into waiting state whenever there was two or more simultaneous execution.

Looking at the Systemjobs, it showed the following error

System.InvalidOperationException: Microsoft Dynamics CRM has experienced an error.
Exception: You cannot create a SqlExecutionContext from another SqlExecutionContext on which OnBeginRequest has not been called


SystemInvalidOperation

Initial thought would say that somewhere there is an open connection which is restricting to execute the workflow but all we had inside that piece of code were CRM service calls.
On researching a bit over this, I came across this great post from Inogic (you can see it here)

Excerpt from the blog:

After searching on net we found that CRM does not re-initialize the plug-in object again, it uses the same object. In the plug-in, ignore to use class level variables. We had created service object at class level so it was using the same service object for retrieving and updating.

After reading this, I quickly went ahead and analyzed the code and found that there was indeed a class level service object that was being used in code (See figure below).

Global Service Context Object

Following Inogic’s suggestion, the class level object was removed and now the code looked like below

ServiceObject

On testing this worked like a charm.
So if you are also facing some issues related to System.InvalidOperationException, then this might really help.

Do let me know in comments if you know a better way to handle this situation or maybe even work with a global service context object without this error. It will really be appreciated.