Monday, March 26, 2012

Workflow Foundation 4 State Machine as a WCF Service

State machine workflow which we had in WF3.5 was not supported in WF4 (in .Net Framework4). But it released with .net framework 4 platform update 1 . State machine is very helpful to model long running workflows with higher external interactions. As an example in a long running order processing system where it needs several user inputs and approvals from external users.
There are several examples state machines in MSDN which describe the state machine well. But here I'm going to expose the state machine as a service. My example is a simple order processing system which has some human interaction to approve orders.

In this workflow there are three states(OrderRecived, To be Approved , Finished) and three triggers (Pay,IssueWithOrder,Resolve). We can create new order by giving an orderId and some amount.Then to complete the order we can pay using Pay trigger. Or else if there any issues with the order we can use another WCF call to workflow to change the state(to restrict pay) using IssueWithOrder trigger. The Resolve trigger is used to resolve the issues when they have any issues.

Download Sample Code

To expose the triggers as services what we need to do is to use send receive activities in triggers.
And the other important thing is correlation handling. Because when we need to call a already instantiated workflow instance we should have some identity to call the correct workflow instance. So in my example the correlation handler is the orderId. Because it is unique for an order which is unique for a workflow instance. So I have a state machine level correlation handler which uses the order id to correlate and each and every WCF call the workflow instance will use that variable as the correlation handler.
You can download my sample code here.


  1. Good concise example, however one problem. It gets hung up if you send the requests out-of-sequence. For instance, create an order, call it with an issue, (don't resolve it) but then call it with Pay.

  2. Hi, i just wanted to know how to communicate with this service?

    1. You can just use it as a WCF service. To test jus use WcfTest client provided with visual studio.


    Any idea about this , I have same issue , my website has service reference added on basis of certain condition i need to decide the workflow databse is that possible.

  4. I downloaded the code and tried to open it in Visual Studio 2015.
    I get error while opening xamlx file- "Activity could not be loaded because of errors in the XAML".
    The error window shows following error-
    Could not find type 'StateMachine' in namespace ''

    Please help me how to resolve this issue