代码改变世界

WCF Basic(2)-服务契约继承

2010-08-26 23:06  Clingingboy  阅读(451)  评论(0编辑  收藏  举报


1 wcf允许接口契约继承,但每个接口必须明确以ServiceContract来声明,不能因为是继承,而忽略了父类的声明.如下声明

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

2.实现

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

3.config配置

<service name = "MyCalculator">
   <endpoint
      address  = "http://localhost:8001/MyCalculator/"
      binding  = "basicHttpBinding"
      contract = "IScientificCalculator"
  />
 </service>
4.客户端生成

[ServiceContract]
 interface ISimpleCalculator
 {
     [OperationContract]
     int Add(int arg1, int arg2);
 }
 class SimpleCalculatorClient : ClientBase<ISimpleCalculator>, ISimpleCalculator
 {
     public int Add(int arg1, int arg2)
     {
         return Channel.Add(arg1, arg2);
     }
     //Rest of the proxy
 }
 
 [ServiceContract]
 interface IScientificCalculator : ISimpleCalculator
 {
     [OperationContract]
     int Multiply(int arg1, int arg2);
 }
 class ScientificCalculatorClient :
                           ClientBase<IScientificCalculator>, IScientificCalculator
 {
     public int Add(int arg1, int arg2)
     {
         return Channel.Add(arg1, arg2);
     }
     public int Multiply(int arg1, int arg2)
     {
         return Channel.Multiply(arg1, arg2);
     }
     //Rest of the proxy
 }


5.客户端可以指向父级接口,配置文件可以指向同一地址

<client>
   <endpoint name = "SimpleEndpoint"
      address  = "http://localhost:8001/MyCalculator/"
      binding  = "basicHttpBinding"
      contract = "ISimpleCalculator"
  />
   <endpoint name = "ScientificEndpoint"
      address  = "http://localhost:8001/MyCalculator/"
      binding  = "basicHttpBinding"
      contract = "IScientificCalculator"
  />
 </client>

6.客户端也可以像接口般继承与调用

SimpleCalculatorClient proxy1 = new SimpleCalculatorClient(  );
 SimpleCalculatorClient proxy2 = new ScientificCalculatorClient(  );
 ScientificCalculatorClient proxy3 = new ScientificCalculatorClient(  );