接口是实现项目的若耦合的,是程序员***用的,WCF有四个常见的接口,下面我们就来详细的看看。WCF提供了四种类型的行为:服务行为、终结点行为、契约行为和操作行为。这四种行为分别定义了四个WCF接口:IServiceBehavior,IEndpointBehavior,IContractBehavior以及IOperationBehavior。
#T#是四个不同的WCF接口,但它们的接口方法却基本相同,分别为AddBindingParameters(),ApplyClientBehavior()以及ApplyDispatchBehavior()。注意,IServiceBehavior由于只能作用在服务端,因此并不包含ApplyClientBehavior()方法。我们可以定义自己的类实现这些WCF接口,但需要注意几点:
1、行为的作用范围,可以用如下表格表示:
2、可以利用自定义特性的方式添加扩展的服务行为、契约行为和操作行为,但不能添加终结点行为;可以利用配置文件添加扩展服务行为和终结点行为,但不能添加契约行为和操作行为。但这些扩展的行为都可以通过ServiceDescription添加。
利用特性添加行为,意味着我们在定义自己的扩展行为时,可以将其派生自Attribute类,然后以特性方式添加。例如:
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Interface)]
publicclassMyServiceBehavior:Attribute,IServiceBehavior...
[MyServiceBehavior]
publicinterfaceIService...
- 1.
- 2.
- 3.
- 4.
如果以配置文件的方式添加行为,则必须定义一个类继承自BehaviorExtensionElement(属于命名空间System.ServiceModel.Configuration),然后重写属性BehaviorType以及CreateBehavior()方法。BehaviorType属性返回的是扩展行为的类型,而CreateBehavior()方法则负责创建该扩展行为的对象实例:
publicclassMyBehaviorExtensionElement:BehaviorExtensionElement
{
publicMyBehaviorExtensionElement(){}
publicoverrideTypeBehaviorType
{
get{returntypeof(MyServiceBehavior);}
}
protectedoverrideobjectCreateBehavior()
{
returnnewMyServiceBehavior();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
如果配置的Element添加了新的属性,则需要为新增的属性应用ConfigurationPropertyAttribute,例如:
[ConfigurationProperty("providerName",IsRequired=true)]
publicvirtualstringProviderName
{
get
{
returnthis["ProviderName"]asstring;
}
set
{
this["ProviderName"]=value;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
配置文件中的配置方法如下所示:
<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>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
注意,在<serviceBehaviors>一节中,<behavior>下的<myBehaviorExtensionElement>就是我们扩展的行为,providerName则是MyBehaviorExtensionElement增加的属性。如果扩展了IEndpointBehavior,则配置节的名称为<endpointBehaviors>。<extensions>节负责添加自定义行为的扩展。其中,<add>中的name值与<behavior>下的<myBehaviorExtensionElement>对应。