using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.Runtime;

namespace WorkflowHost
{
    public static class WorkflowFactory
    {
        //workflow runtime的单一实例
        private static WorkflowRuntime _workflowRuntime = null;
        private static object _syncRoot = new object();
        //工厂方法
        public static WorkflowRuntime GetWorkflowRuntime()
        {
            //多线程环境下防止并发访问
            lock (_syncRoot)
            {
                if (null == _workflowRuntime)
                {
                    AppDomain.CurrentDomain.ProcessExit += new EventHandler(StopWorkflowRuntime);
                    AppDomain.CurrentDomain.DomainUnload += new EventHandler(StopWorkflowRuntime);
                    _workflowRuntime = new WorkflowRuntime();
                    _workflowRuntime.StartRuntime();
                }
            }
            return _workflowRuntime;
        }
        static void StopWorkflowRuntime(object sender, EventArgs e)
        {
            if (_workflowRuntime != null)
            {
                if (_workflowRuntime.IsStarted)
                {
                    try
                    {
                        _workflowRuntime.StopRuntime();
                    }
                    catch (ObjectDisposedException)
                    {
                    }
                }
            }
        }
    }
}
