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

WCF 實戰 (7) Part II:SOA 與 OOP 無縫整合 — 客戶端繼承架構 Proxy 重構實戰

     編輯:關於.NET

背景回顧

Part I 已完成服務端 Contract 繼承體系:IFullWhetherForecast : ISimpleWhetherForecast,服務類別 FullWhetherForecastService : SimpleWhetherForecastService。僅暴露最底層 Contract 端點。現須在客戶端重建同樣的繼承架構,而非接受扁平化的產生式 Proxy。

一、添加服務參考產生的預設程式碼分析

1. Data Contract 完整保留 (含 Enum、KnownType)

但遺失原始類別的 ToString() 覆寫 — 代碼產生器僅處理資料成員。

2. Service Contract 扁平化

產生單一 IFullWhetherForecast 包含所有 Operation,喪失繼承階層。

3. Proxy 類別單一

FullWhetherForecastClient 直接實作扁平 Contract,無繼承關係。

二、手工重構客戶端繼承架構 (四步驟)

Step 1: 定義客戶端 Contract 階層 (與服務端鏡像)

// ISimpleWhetherForecast.cs
[ServiceContract]
public interface ISimpleWhetherForecast
{
    [OperationContract] BasicWhetherInfo GetBasicWhetherInfo(string postalcode);
}

// IFullWhetherForecast.cs
[ServiceContract]
public interface IFullWhetherForecast : ISimpleWhetherForecast
{
    [OperationContract] WindInfo GetWindInfo(string postalcode);
}

Step 2: 引用共用 BusinessEntity 組件 (Data Contract 共享)

避免重複定義,確保序列化一致性。

Step 3: 設定端點對應最底層 Contract

<endpoint address="https://localhost/.../FullWhetherForecastService.svc"
          binding="wsHttpBinding"
          contract="Artech.InheritanceHierarchy.Client.IFullWhetherForecast" />

Step 4: 建立繼承關係的 Proxy 類別

// SimpleWhetherForecastClient.cs
public class SimpleWhetherForecastClient : ClientBase<IFullWhetherForecast>, ISimpleWhetherForecast
{
    public BasicWhetherInfo GetBasicWhetherInfo(string postalcode) => Channel.GetBasicWhetherInfo(postalcode);
}

// FullWhetherForecastClient.cs
public class FullWhetherForecastClient : SimpleWhetherForecastClient, IFullWhetherForecast
{
    public WindInfo GetWindInfo(string postalcode) => Channel.GetWindInfo(postalcode);
}

三、驗證優雅呼叫

using (var simple = new SimpleWhetherForecastClient())
{
    var basic = simple.GetBasicWhetherInfo("10001");
}

using (var full = new FullWhetherForecastClient())
{
    var basic = full.GetBasicWhetherInfo("10001"); // 繼承自基底 Proxy
    var wind = full.GetWindInfo("10001");
}

四、核心價值

  • 契約優先:客戶端 Contract 階層與服務端完全對齊,編譯期檢查繼承關係。
  • 多型複用:基底 Proxy 可作為參數傳遞,支援 Liskov 替換原則。
  • 關注點分離:簡易客戶端僅依賴 ISimpleWhetherForecast,不受完整功能變更影響。
  • 零侵入服務端:服務端僅暴露單一端點,客戶端自行組裝架構。

總結

WCF 不強制客戶端接受扁平化 Proxy。透過 ClientBase<T> 泛型參數指定最底層 Contract,配合 C# 介面繼承與類別繼承,即可在客戶端重建豐富的 OO 架構,實現 SOA 服務契約與 OOP 程式模型的完美融合。

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