I recently wrote an application which I needed to have run every few hours. I decided that it would run as an NT service but didn’t want to write the code to persist and load application state and deal with scheduling execution of the app.
I decided to use WF since it takes care of those requirements for me but I couldn’t find a sample where it had been hosted in a NT/Windows service. So here is an example and walk through of how to do so.
First, you’ll need to create a Windows Service application. There are a few non-WF specific steps here to get an NT service up and running.
Change [assembly: ComVisible(false)] to [assembly: ComVisible(true)]
Write an Installer class which is invoked by InstallUtil.exe to register the service
I deleted the default Program.cs the Windows Service template creates and moved the Main() method to the Service Definition. For ease of debugging, I’ve also modified it to run from the console.
Ok, lets get to hosting WF.
First, we’ll scope the workflow runtime to the lifetime of the service:
public partial class Service1 : ServiceBase
WorkflowRuntime WFRT = new WorkflowRuntime();
static void Main(string args)
In the Service OnStart() method, you’ll notice this line of code:
protected override void OnStart(string args)
A Windows Service requires that OnStart() return fairly quickly and if you’re creating of a number of workflow instances it can take more time than the service allows. Thus I use QueueUserWorkItem with the callback specified below. For a single workflow instance, this is a bit heavy handed, but still a good practice.
public void RunWorkflow(object obj)
WorkflowInstance instance = WFRT.CreateWorkflow(typeof(Workflow1));
This is now going to kick off a very simple workflow, which every 5 seconds will write a simple message to the event log. You can find the code for this project here.