先看看System.Activities.Hosting.SymbolResolver 的定义:
public sealed class SymbolResolver : IDictionary<string, Object>,
ICollection<KeyValuePair<string, Object>>, IEnumerable<KeyValuePair<string, Object>>,
IEnumerable
实现了IDictionary<string, Object> 接口,我们在工作流宿主中将需要在自定义Activity中访问的变量加入到SymbolResolver 中,然后在Activity中获取
SymbolResolver 实例,再通过key访问需要的变量,代码如下:
//定义信息包装类:
public class MyObject
{
public int MyValue { get; set; }
public string MyString { get; set; }
}
//将SymbolResolver作为Extension加入到WorkflowApplication中
class Program
{
static void Main(string[] args)
{
WorkflowApplication WFApp = new WorkflowApplication(new Workflow1());
SymbolResolver symbolResolver = new SymbolResolver();
WFApp.Extensions.Add(symbolResolver);
symbolResolver.Add("CustomObject", new SymbolUserActivity.MyObject() { MyValue = 1, MyString = "TestString" });
WFApp.Run();
Console.ReadLine();
}
}
//在自定义活动中访问MyObject实例
public sealed class SymbolUser : CodeActivity
{
protected override void Execute(CodeActivityContext context)
{
SymbolResolver symbolResolver = context.GetExtension<SymbolResolver>();
MyObject obj = symbolResolver["CustomObject"] as MyObject;
Console.WriteLine(obj.MyString);
}
}
最后要注意的是: SymbolResolver 不会参与工作流持久化过程。
原文:Using a WF4 SymbolResolver to access host environment information