Self Hosting Receive Activity
Last changed: -80.126.16.139

.
Summary

Hosting the workflow runtime in a WorkflowServiceHost is nice but in all likelihood you will also need to configure the workflow runtime itself and add some WorkflowRuntimeService to it. So how to do this when you never actually create the workflow runtime yourself?

There are two possible ways to go about this depending if you prefer to use code or a configuration file. Lets first look at the code option as it is easier to see all the working parts. In the case of a WCF hosted workflow runtime the WorkflowRuntimeBehavior is the WCF ServiceBehavior that is actually responsible for creating the WorkflowRuntime. Fortunately getting a reference to it, and thereby the WorkflowRuntime, isn't hard.

// Create the host
WorkflowServiceHost host = new WorkflowServiceHost(typeof(Workflow1));
// Retreive the WF behavior
WorkflowRuntimeBehavior workflowRuntimeBehaviour =
host.Description.Behaviors.Find<WorkflowRuntimeBehavior>();
// Retreive the WF runtime
WorkflowRuntime workflowRuntime = workflowRuntimeBehaviour.WorkflowRuntime;
// Create and add the SqlWorkflowPersistenceService
SqlWorkflowPersistenceService persistenceService =
   new SqlWorkflowPersistenceService(connectionString);
workflowRuntime.AddService(persistenceService);
// Start listening
host.Open();

Doing the same in a configuration file isn't hard either. The main problem is that a app.config isn't compiled so it's a bit easier to make a typo and not catch it until runtime.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <!-- Details ommited -->
    <behaviors>
      <serviceBehaviors>
        <behavior name="WorkflowConsoleApplication1.Workflow1Behavior" >
          <!-- Details ommited -->
          <workflowRuntime name="WorkflowServiceHostRuntime"
                           validateOnCreate="true"
                           enablePerformanceCounters="true">
            <services>
              <add type="System.Workflow.Runtime.Hosting.SqlWorkflowPersistenceService, 
                         System.Workflow.Runtime, Version=3.0.00000.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                   connectionString="Data Source=localhost\sqlexpress;Initial Catalog=WorkflowPersistence;Integrated Security=True;Pooling=False"
                   LoadIntervalSeconds="1"
                   UnLoadOnIdle= "true" />
            </services>
          </workflowRuntime>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

This configuration file is basically the same as in the previous post except that contains a workflowRuntime element inside of the service behavior. This workflowRuntime contains the services collection where you can add any services you need.