workflow-foundation-4workflow-activity

Passing Lambda expression to Workflow Code Activity as a parameter


I am wondering if Lambda expression could be passed to Windows workflow Code Activity as a parameter?

I am trying to query ldap for user objects based on a lambda expression which would be passed to a Windows workflow Code Activity as a parameter.


Solution

  • A lamda expression is just a reference, pass it as you would any other data.

    class Program
    {
        static void Main(string[] args)
        {
            var workflow = new ExecuteFunc<int>();
            var inputs = new Dictionary<string, object>();
            inputs["Func"] = new Func<int, int>(maxValue =>
            {
                var rnd = new Random(Environment.TickCount);
                return rnd.Next(maxValue);
            });
            inputs["MaxValue"] = 100;
            WorkflowInvoker.Invoke(workflow, inputs);
        }
    }
    
    public class ExecuteFunc<T> : CodeActivity<T>
    {
        public InArgument<int> MaxValue { get; set; }
        public InArgument<Func<int, T>> Func { get; set; }
    
        protected override T Execute(CodeActivityContext context)
        {
            var func = Func.Get(context);
            var maxValue = MaxValue.Get(context);
            var result = func(maxValue);
            Console.WriteLine(result);
            return result;
        }
    }