Search code examples
workflow-foundation-4workflow-foundationworkflow-activity

Workflow instance is singleton? Control activity instancing?


Can I control if an activity of a workflow is a singleton or not? I discovered the same activity class instance within a workflow is (re)used every time the workflow is executed.

Or simply said, in Execute() method of the activity method I get a different context.WorkflowInstanceId, but the same context.ActivityInstanceId.

Is this by design? By default?

Can I control activity instancing? Can I have a new instance of activity every time the workflow is executed?


Solution

  • Yes it is the default behavior. An activity instance can be the same instance in a miltithreaded enviroment (web context) which can bite you. So to be safe you should always have all your activity variables as Argument. Arguments are passed via ActivityContext which is different for each activity instance.

    public class CustomActivity : Activity
    {
       public int Age { get; set; }
    
       protected override void Execute(CodeActivityContext context)
       {
            //do some work with Age 
       }
    }
    

    Since different threads can set/get that same instance variable, instead of the code above you should do this:

    public class CustomActivity : Activity
    {
       public InOutArgument<int> Age { get; set; }
    
       protected override void Execute(CodeActivityContext context)
       {
            //do some work with Age within CodeActivityContext 
       }
    }