揭秘四種行為WCF接口使用
接口是實(shí)現(xiàn)項(xiàng)目的若耦合的,是程序員***用的,WCF有四個(gè)常見的接口,下面我們就來(lái)詳細(xì)的看看。WCF提供了四種類型的行為:服務(wù)行為、終結(jié)點(diǎn)行為、契約行為和操作行為。這四種行為分別定義了四個(gè)WCF接口:IServiceBehavior,IEndpointBehavior,IContractBehavior以及IOperationBehavior。
#T#是四個(gè)不同的WCF接口,但它們的接口方法卻基本相同,分別為AddBindingParameters(),ApplyClientBehavior()以及ApplyDispatchBehavior()。注意,IServiceBehavior由于只能作用在服務(wù)端,因此并不包含ApplyClientBehavior()方法。我們可以定義自己的類實(shí)現(xiàn)這些WCF接口,但需要注意幾點(diǎn):
1、行為的作用范圍,可以用如下表格表示:
2、可以利用自定義特性的方式添加擴(kuò)展的服務(wù)行為、契約行為和操作行為,但不能添加終結(jié)點(diǎn)行為;可以利用配置文件添加擴(kuò)展服務(wù)行為和終結(jié)點(diǎn)行為,但不能添加契約行為和操作行為。但這些擴(kuò)展的行為都可以通過(guò)ServiceDescription添加。
利用特性添加行為,意味著我們?cè)诙x自己的擴(kuò)展行為時(shí),可以將其派生自Attribute類,然后以特性方式添加。例如:
- [AttributeUsage(AttributeTargets.Class|AttributeTargets.Interface)]
- publicclassMyServiceBehavior:Attribute,IServiceBehavior...
- [MyServiceBehavior]
- publicinterfaceIService...
如果以配置文件的方式添加行為,則必須定義一個(gè)類繼承自BehaviorExtensionElement(屬于命名空間System.ServiceModel.Configuration),然后重寫屬性BehaviorType以及CreateBehavior()方法。BehaviorType屬性返回的是擴(kuò)展行為的類型,而CreateBehavior()方法則負(fù)責(zé)創(chuàng)建該擴(kuò)展行為的對(duì)象實(shí)例:
- publicclassMyBehaviorExtensionElement:BehaviorExtensionElement
- {
- publicMyBehaviorExtensionElement(){}
- publicoverrideTypeBehaviorType
- {
- get{returntypeof(MyServiceBehavior);}
- }
- protectedoverrideobjectCreateBehavior()
- {
- returnnewMyServiceBehavior();
- }
- }
如果配置的Element添加了新的屬性,則需要為新增的屬性應(yīng)用ConfigurationPropertyAttribute,例如:
- [ConfigurationProperty("providerName",IsRequired=true)]
- publicvirtualstringProviderName
- {
- get
- {
- returnthis["ProviderName"]asstring;
- }
- set
- {
- this["ProviderName"]=value;
- }
- }
配置文件中的配置方法如下所示:
- <configuration>
- <system.serviceModel>
- <services>
- <servicenameservicename="MessageInspectorDemo.Calculator">
- <endpointbehaviorConfigurationendpointbehaviorConfiguration="messageInspectorBehavior"
- address="http://localhost:801/Calculator"
- binding="basicHttpBinding"
- contract="MessageInspectorDemo.ICalculator"/>
- </service>
- </services>
- <behaviors>
- <serviceBehaviors>
- <behaviornamebehaviorname="messageInspectorBehavior">
- <myBehaviorExtensionElementproviderNamemyBehaviorExtensionElementproviderName="Test"/>
- </behavior>
- </serviceBehaviors>
- </behaviors>
- <extensions>
- <behaviorExtensions>
- <addnameaddname="myBehaviorExtensionElement"
- type="MessageInspectorDemo.MyBehaviorExtensionElement,MessageInspectorDemo,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null"/>
- </behaviorExtensions>
- </extensions>
- </system.serviceModel>
- </configuration>
注意,在<serviceBehaviors>一節(jié)中,<behavior>下的<myBehaviorExtensionElement>就是我們擴(kuò)展的行為,providerName則是MyBehaviorExtensionElement增加的屬性。如果擴(kuò)展了IEndpointBehavior,則配置節(jié)的名稱為<endpointBehaviors>。<extensions>節(jié)負(fù)責(zé)添加自定義行為的擴(kuò)展。其中,<add>中的name值與<behavior>下的<myBehaviorExtensionElement>對(duì)應(yīng)。