揭秘四种行为WCF接口使用

接口是实现项目的若耦合的,是程序员***用的,WCF有四个常见的接口,下面我们就来详细的看看。WCF提供了四种类型的行为:服务行为、终结点行为、契约行为和操作行为。这四种行为分别定义了四个WCF接口:IServiceBehavior,IEndpointBehavior,IContractBehavior以及IOperationBehavior。

成都创新互联公司是一家专业提供武定企业网站建设,专注与网站建设、网站设计H5响应式网站、小程序制作等业务。10年已为武定众多企业、政府机构等服务。创新互联专业网站设计公司优惠进行中。

#T#是四个不同的WCF接口,但它们的接口方法却基本相同,分别为AddBindingParameters(),ApplyClientBehavior()以及ApplyDispatchBehavior()。注意,IServiceBehavior由于只能作用在服务端,因此并不包含ApplyClientBehavior()方法。我们可以定义自己的类实现这些WCF接口,但需要注意几点:
1、行为的作用范围,可以用如下表格表示:
2、可以利用自定义特性的方式添加扩展的服务行为、契约行为和操作行为,但不能添加终结点行为;可以利用配置文件添加扩展服务行为和终结点行为,但不能添加契约行为和操作行为。但这些扩展的行为都可以通过ServiceDescription添加。

利用特性添加行为,意味着我们在定义自己的扩展行为时,可以将其派生自Attribute类,然后以特性方式添加。例如:

 
 
  1. [AttributeUsage(AttributeTargets.Class|AttributeTargets.Interface)]  
  2. publicclassMyServiceBehavior:Attribute,IServiceBehavior...  
  3. [MyServiceBehavior]  
  4. publicinterfaceIService... 

如果以配置文件的方式添加行为,则必须定义一个类继承自BehaviorExtensionElement(属于命名空间System.ServiceModel.Configuration),然后重写属性BehaviorType以及CreateBehavior()方法。BehaviorType属性返回的是扩展行为的类型,而CreateBehavior()方法则负责创建该扩展行为的对象实例:

 
 
  1. publicclassMyBehaviorExtensionElement:BehaviorExtensionElement  
  2. {  
  3. publicMyBehaviorExtensionElement(){}  
  4. publicoverrideTypeBehaviorType  
  5. {  
  6. get{returntypeof(MyServiceBehavior);}  
  7. }  
  8.  
  9. protectedoverrideobjectCreateBehavior()  
  10. {  
  11. returnnewMyServiceBehavior();  
  12. }  
  13. }  

如果配置的Element添加了新的属性,则需要为新增的属性应用ConfigurationPropertyAttribute,例如:

 
 
  1. [ConfigurationProperty("providerName",IsRequired=true)]  
  2. publicvirtualstringProviderName  
  3. {  
  4. get  
  5. {  
  6. returnthis["ProviderName"]asstring;  
  7. }  
  8. set  
  9. {  
  10. this["ProviderName"]=value;  
  11. }  

配置文件中的配置方法如下所示:

 
 
  1.  
  2.  
  3.  
  4. <servicenameservicename="MessageInspectorDemo.Calculator"> 
  5. <endpointbehaviorConfigurationendpointbehaviorConfiguration="messageInspectorBehavior" 
  6. address="http://localhost:801/Calculator" 
  7. binding="basicHttpBinding" 
  8. contract="MessageInspectorDemo.ICalculator"/> 
  9.  
  10.  
  11.  
  12.  
  13. <behaviornamebehaviorname="messageInspectorBehavior"> 
  14. <myBehaviorExtensionElementproviderNamemyBehaviorExtensionElementproviderName="Test"/> 
  15.  
  16.  
  17.  
  18.  
  19.  
  20. <addnameaddname="myBehaviorExtensionElement" 
  21. type="MessageInspectorDemo.MyBehaviorExtensionElement,MessageInspectorDemo,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null"/> 
  22.  
  23.  
  24.  
  25.  

注意,在一节中,下的就是我们扩展的行为,providerName则是MyBehaviorExtensionElement增加的属性。如果扩展了IEndpointBehavior,则配置节的名称为节负责添加自定义行为的扩展。其中,中的name值与下的对应。

名称栏目:揭秘四种行为WCF接口使用
网页URL:http://www.hantingmc.com/qtweb/news48/534848.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联