2010-12-02 42 views
2

如何在.NET 4下的Windows Workflow Foundation活動中從父範圍動態設置變量的值?從WF 4活動動態設置外部範圍變量

失敗(上一個工作流程,序列有一個名爲測試一個int變量上的一系列活動下降)的嘗試:

public sealed class CodeActivity1 : NativeActivity 
{ 
    protected override void CacheMetadata(NativeActivityMetadata metadata) 
    { 
     _locationReferences = 
      metadata.Environment.GetLocationReferences().ToList(); 

     base.CacheMetadata(metadata); 
    } 

    protected override void Execute(NativeActivityContext context) 
    { 
     LocationReference locationReference = 
      _locationReferences.Find(
       x => x.Name == "Test" && x.Type == typeof (int)); 

     if (locationReference != null) 
     { 
      Console.WriteLine(
       locationReference.Name + " " + locationReference.Type); 

      // Blows up here. 
      Location location = locationReference.GetLocation(context); 
      location.Value = 5; 
     } 
    } 

    private List<LocationReference> _locationReferences; 
} 

這導致:

System.InvalidOperationException了 用戶代碼未處理
消息=活動「1.2:CodeActivity1」 無法訪問此變量,因爲它在活動範圍處聲明瞭'1.1:序列'。一個活動只能訪問 變量。

它找到了變量;它只是無法獲得或設定其價值。

直到運行時才能知道變量名稱(上例中的「測試」)。

回答

6

處理此問題的常規方法是定義OutArgument,並在工作流設計器中將OutArgument綁定到變量。在這個活動中,你只能使用參數。使用NativeActivity會爲您提供名爲Result的OutArgument,但只需添加OUtArgument的屬性就可以了。

另一個好處是,你不需要知道「魔術」變量名來存儲結果。

更新,因爲在下面的評論的代碼不可讀。

嘗試添加以下只是行前炸燬:

var pi = context.GetType().GetProperty("AllowChainedEnvironmentAccess", BindingFlags.NonPublic | BindingFlags.Instance); 
pi.SetValue(context, true, null); 

完全不支持這麼謹慎使用:-)

+0

我有一個客戶端沒有硬編碼的知識要求工作流程。我們習慣於BPM,您可以通過傳入名稱,值對來初始化字段,詢問正在運行的進程以獲取字段列表然後設置它們等來創建進程。它更靈活,可發現並且解耦運行時安全的成本。從BPM轉向WF就像是從動態類型語言轉變爲靜態類型語言。我認爲我們有兩個選擇:用類型爲Dictionary 的變量僞造它,或者詢問WSDL。 – TrueWill 2010-12-03 15:52:19