Dot-Net

WCF中契約的繼承

  • October 17, 2017

我在測試工具中有幾個 WCF 服務,它們具有一些類似的功能,例如被測分佈式系統的啟動/停止/清理部分。我不能使用通用合約來做到這一點——分佈式系統的每個部分對這些操作都有不同的步驟。

我正在考慮定義一個基本介面並從中派生目前的 WCF 介面。

例如:

interface Base
{
   void BaseFoo();
   void BaseBar();
   ...
}

interface Child1:Base
{
   void ChildOperation1();
   ...
}

interface Child2:Base
{
   void ChildOperation2();
   ...
}

我現在擁有的是在每個子界面​​中定義的那些啟動/停止/清理操作。

Q我應該將類似的功能提取到基本界面中還是有其他解決方案?在 WCF 中繼承契約會有什麼問題嗎?

服務契約介面可以相互派生,使您能夠定義契約的層次結構。但是,ServiceContract attribute is not inheritable

[AttributeUsage(Inherited = false,...)]
public sealed class ServiceContractAttribute : Attribute
{...}

因此,介面層次結構中的每個級別都必須明確具有服務契約屬性。

服務端合約層次結構:

[ServiceContract]
interface ISimpleCalculator
{
   [OperationContract]
   int Add(int arg1,int arg2);
}
[ServiceContract]
interface IScientificCalculator : ISimpleCalculator
{
   [OperationContract]
   int Multiply(int arg1,int arg2);
}

在實現契約層次結構時,單個服務類可以實現整個層次結構,就像經典 C# 程式一樣:

class MyCalculator : IScientificCalculator
{
   public int Add(int arg1,int arg2)
   {
       return arg1 + arg2;
   }
   public int Multiply(int arg1,int arg2)
   {
       return arg1 * arg2;
   }
}

主機可以為層次結構中最底層的介面公開一個端點:

<service name = "MyCalculator">
   <endpoint
   address = "http://localhost:8001/MyCalculator/"
   binding = "basicHttpBinding"
   contract = "IScientificCalculator"
   />
</service>

您不必擔心契約層次結構。

Juval Lowy WCF 書籍的啟發

引用自:https://stackoverflow.com/questions/6955421