首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

WF 4.0 實戰(三):在工作流中建立與呼叫 WCF 服務

     編輯:關於.NET

前言

WF 4.0 內建 Messaging 活動組(Receive、ReceiveAndSendReply、Send、SendAndReceiveReply),讓開發者能在工作流設計器中以視覺化方式定義 WCF 服務合約、繫結與位址(ABC)。本文透過一個圖書預約範例,詳細說明如何在 WF 中實作服務端與客戶端。

資料合約定義

Request:ReservationRequest

[MessageContract(IsWrapped = false)]
public class ReservationRequest
{
    [MessageBodyMember] public String Title { get; set; }
    [MessageBodyMember] public String ISBN { get; set; }
    [MessageBodyMember] public String Author { get; set; }
    [MessageBodyMember] public Guid RequestID { get; set; }
    [MessageBodyMember] public Branch Requester { get; set; }
    [MessageBodyMember] public Guid InstanceID { get; set; }
    // 建構子略...
}

Response:ReservationResponse

[MessageContract(IsWrapped = false)]
public class ReservationResponse
{
    [MessageBodyMember] public bool Reserved { get; set; }
    [MessageBodyMember] public Branch Provider { get; set; }
    [MessageBodyMember] public Guid RequestID { get; set; }
    // 建構子略...
}

服務合約介面

[ServiceContract]
public interface ILibraryReservation
{
    [OperationContract] void RequestBook(ReservationRequest request);
    [OperationContract] void RespondToRequest(ReservationResponse response);
}

服務端實作

1. 合約(Contract)

在工作流 ProcessRequest 中拖放 ReceiveAndSendReply 活動:

  • Receive 設定 OperationName=RequestBook、ServiceContractName=ILibraryReservation、訊息內容型別為 ReservationRequest。
  • SendReply 設定回覆訊息型別為 ReservationResponse。
  • 中間插入自訂活動 CreateResponse 組裝回應物件。

流程設計圖:

服務端流程

2. 繫結與位址

以程式碼啟動 WorkflowServiceHost:

WorkflowService service = new WorkflowService
{
    Name = "LibraryReservation",
    Body = new ProcessRequest(),
    Endpoints = {
        new Endpoint {
            ServiceContractName = "ILibraryReservation",
            AddressUri = new Uri("https://localhost:" + port + "/LibraryReservation"),
            Binding = new BasicHttpBinding()
        }
    }
};
WorkflowServiceHost wsh = new WorkflowServiceHost(service);
wsh.Open();

客戶端呼叫

客戶端同樣使用工作流 SendRequest,拖放 SendAndReceiveReply 活動:

  • 前置 CreateRequest 活動建立 ReservationRequest。
  • Send 設定目標端點、合約、操作名稱。
  • ReceiveReplyForSend 接收 ReservationResponse。

呼叫程式碼:

IDictionary<string, object> input = new Dictionary<string, object> {
    {"Title", "Gone with the Wind"},
    {"Author", "Margaret Mitchell"},
    {"ISBN", "9781416548898"}
};
IDictionary<string, object> output = WorkflowInvoker.Invoke(new SendRequest(), input);
ReservationResponse resp = (ReservationResponse)output["Response"];

執行結果

服務端啟動等待:

服務端執行畫面

客戶端呼叫後輸出:

客戶端輸出

完整互動序列圖:

互動序列

總結

WF 4.0 的 Messaging 活動將 WCF 的 ABC 設定視覺化,開發者無需撰寫大量樣板碼即可在工作流中發布與消費服務,極大簡化了服務整合開發。

原始碼

本文配套原始碼已提供(下載連結請參考原文)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved