WCF之旅——Contract

翻译|其它|编辑:郝浩|2007-12-29 11:02:22.000|阅读 879 次

概述:

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

      1.ServiceContract&OperationContract General

      Contract 定义了这一个 Service 能提供什么样的功能和服务(ServiceContract),也告诉了调用这一 Service 的客户端或者其它的 Service 在调用时需要提供什么样的参数信息(DataContract)。因此,在 SOA 架构的系统中,Contract 的定义是重中之重。本文将对 ServiceContract 做一个简单的介绍。

      在 WCF 中,给一个 interface(或者 class)添加一个[ServiceContract]的 Attribute, 这个 interface 就成为一个面向服务的 contract(service-oriented contract)。你可以使用你自己喜欢的变成语言来写这个 interface,比如 C#, C++, VB.Net 等。只要它符合.net framework 的 CTS(Common Type Specification)。SeriveContract 使得一个 interface 成为一个 WCF 的 contract, 而不再具有类型的可见性(type’s visibility)这一属性。成为一个 contract 之后,它就成为一个共有的 service contract. 而普通的 interface 对于 WCF Service 的调用者来说,完全是透明的的,也根本就不知道这个 interface 的存在。

      一个 interface 要成一个 WCF 的 Contract,需要给这个 interface 加上[ServiceContract]这一个特性(Attribute),而要这个 contract 成为一个有用的 contract, 还需要给这个 interface 中希望暴露的方法加上[OperationContract]这一特性。否者,这个 interface 中所有的方法,对于调用这个 service 的 client 来说,都是不可见的。

Eg:

[ServiceContract]
interface IMyContract1
{
   [OperationContract]
   string MyMethod1( );
}
[ServiceContract]
interface IMyContract2
{
   [OperationContract]
   void MyMethod2( );
}

class MyService : IMyContract1,IMyContract2
{
   public string MyMethod1( )
   {...}
   public void MyMethod2( )
   {...}
}

从示例代码钟还可以看出,WCF 的多重实现(Multiple Implementation )。

2.OperationContract之Operation 重载
WCF Contract 的实现也支持重载,只不过需要做一些额外的工作。

//Invalid contract definition:
[ServiceContract]
interface ICalculator
{
   [OperationContract]
   int Add(int arg1,int arg2);

   [OperationContract]
   double Add(double arg1,double arg2);
}
运行上面的代码会在 ServiceHost 加载 service 的时候抛出一个:InvalidOperationException。

WCF 对一个 Operation 提供了一个叫做 Name 的 Attribute, 利用这个 Name 可以实现重载,如:

[ServiceContract]
interface ICalculator
{
   [OperationContract(Name = "AddInt")]
   int Add(int arg1,int arg2);

   [OperationContract(Name = "AddDouble")]
   double Add(double arg1,double arg2);
}
只不过有一个不足之处是生成的 Proxy 的代码相应的函数名将会是 AddInt 和 AddDouble。不过你要是愿意的话可以手动修改生成的函数,但是要确保调用了正确的 internal proxy 的方法。

3.ServiceContract 之继承

WCF Contracts 之间支持继承等操作,因此可以建立一个具有层级关系的 Contracts。但是[ServiceContract]这一特性不能被继承,因此必须在每一个 interface 上加上这一特性。

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

但是当把 IMyCalculator 这个 Service 暴露给 Client, 并用工具生成 Proxy 代码时,生成大代码将不具有这种层级关系。


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@evget.com

文章转载自:.NET博客园

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP