Managing the WorkflowRuntime In ASP.NET

Monday, January 15, 2007

If you want to use Windows Workflow in ASP.NET, you'll need create and maintain a WorkflowRuntime instance. What's the easiest approach to use?

The easiest approach (not necessarily the best), is to use global.asax.

<%@ Application Language="C#" %>
<%
@ Import Namespace="System.Workflow.Runtime" %>

<script runat="server">    
    
    
void Application_Start(object sender, EventArgs e)
    {
        InitializeWorkflowRuntime();

    }
    
    
void Application_End(object sender, EventArgs e)
    {
        
if (_workflowRuntime != null)
        {
            _workflowRuntime.Dispose();
        }

    }      

    
void InitializeWorkflowRuntime()
    {
        _workflowRuntime =
new WorkflowRuntime();
        
        
// ... additional configuration ...
        
    }
    
    
public WorkflowRuntime WorkflowRuntime
    {
        
get { return _workflowRuntime; }
    }
        
    
private WorkflowRuntime _workflowRuntime;
      
</script>

This approach gives us a WorkflowRuntime we can reach from any page. Remember, in an ASP.NET Web Site project, the runtime code-generates a strongly-typed ApplicationInstance property from global.asax for each web form. We can access the WorkflowRuntime property defined in global.asax with ease:

protected void Page_Load(object sender, EventArgs e)
{
    
// ...

    ApplicationInstance.WorkflowRuntime.CreateWorkflow( /* ... */ );

    
// ...
}

This approach is simple, straightforward, and easy, but let's think about the disadvantages.

First, global.asax makes the WF runtime readily available to the web application, but it's not so easy to obtain this reference from a data, business, or service layer. It's possible - but not pretty.

Secondly, global.asax can cause headaches. I tend to avoid adding global.asax to a project, as once the file comes into play it tends to become a dumping ground for global "stuff" that an application needs.

Generally speaking, a better approach is to manage the WF runtime from a lower layer in the application architecture. Using a Registry or Service Locator type pattern makes the runtime available through all layers of the application. Error reporting, logging, and tracking of workflows and their runtime can live inside one or more dedicated components. This approach requires a little more work, but provides the flexibility required for larger applications. More details to come.


Comments
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!