Wednesday, June 27, 2007

The workflow hosting environment does not have a persistence service as required by an operation on the workflow instance

When you run a Workflow which does not have a persistence service, you may encounter the following error : The workflow hosting environment does not have a persistence service as required by an operation on the workflow instance. This blog explains the cause, and tells you how to fix it.
--------------------------------------------------------------------------------

When you run a Workflow which does not have a persistence service, you may encounter the following error : The workflow hosting environment does not have a persistence service as required by an operation on the workflow instance "d0d830f6-afd5-42c5-8e16-10437417caf6".

Let's have a look at this sample:

Create a workflow with a CompensatableTransactionScope, and a CodeActivity within the CompensatableTransactionScope, which outputs a message to the Console e.g. Console.WriteLine("Hello Workflow");

If you run the application, you will obtain the error above. This is because Persistence is built into the CompensatableTransactionScope, and a "persistence point" will occur automatically whenever the Transaction completes.

A "Persistence Point" occurs in the following scenarios:

- When workflow becomes idle AND the unloadOnIdle flag for the persistence service is true. E.g. Delay Activity
- Host application calls WorkflowInstance.Unload or WorkflowInstance.RequestPersist

If any of the following objects complete their work. e.g.:
- a Workflow terminates or finishes.
- a custom Activity using PersistOnClose attribute finishes
- a CompensatableSequenceActivity is completed
- an Atomic transaction completes : TransactionScopeActivity / CompensatableTransactionScopeActivity

The way to solve our dilemma is to add a persistence service to the WorkflowRuntime, as follows:

SqlWorkflowPersistenceService sqlPersistenceService = new SqlWorkflowPersistenceService("Initial Catalog=SqlPersistenceService;Data Source=localhost;Integrated Security=SSPI");
workflowRuntime.AddService(sqlPersistenceService);


Now run the application, and your persistence problem is solved.

No comments: