剖析WCF配置全过程

如果WCF配置为空,那么endpoint的地址就是默认的基地址(Base Address)。例如WCF配置的地址就是http://localhost/servicemodelsamples/service.svc,而IMetadataExchange服务的地址则为http://localhost/servicemodelsamples/service.svc/mex。这里所谓的基地址可以在<service>中通过配置<host>来定义:

 
 
  1. <service 
  2. name="Microsoft.ServiceModel.Samples.CalculatorService" 
  3. behaviorConfiguration="CalculatorServiceBehavior"> 
  4. <host> 
  5. <baseAddresses> 
  6. <add baseAddress=  
  7. "http://localhost/ServiceModelSamples/service.svc"/> 
  8. </baseAddresses> 
  9. </host> 
  10. <endpoint … /> 
  11. </service> 

当我们在定义一个实现了Service Contract的类时, binding和address信息是客户端必须知道的,否则无法调用该服务。然而,如果需要指定服务在执行方面的相关特性时,就必须定义服务的behavior。在WCF中,定义behavior就可以设置服务的运行时属性,甚至于通过自定义behavior插入一些自定义类型。例如通过指定ServiceMetadataBehavior,可以使WCF服务对外公布Metadata。WCF配置如下:

 
 
  1. <behaviors> 
  2. <serviceBehaviors> 
  3. <behavior name="metadataSupport"> 
  4. <serviceMetadata httpGetEnabled="true" httpGetUrl=""/> 
  5. </behavior> 
  6. <serviceBehaviors> 
  7. <behaviors> 

WCF配置中,behavior被定义为Attribute,其中,System.ServiceModel.ServiceBehaviorAttribute和System.ServiceModel.OperationBehaviorAttribute是最常用的behavior。虽然,behavior作为Attribute可以通过编程的方式直接施加到服务上,但出于灵活性的考虑,将behavior定义到WCF配置文件中才是***的设计方式。#t#

利用ServiceBehavior与OperationBehavior可以控制服务的如下属性:

 
 
  1. <behaviors> 
  2. <serviceBehaviors> 
  3. <behavior name="metadataSupport"> 
  4. <instanceContextMode httpGetEnabled="true" httpGetUrl=""/> 
  5. </behavior> 
  6. <serviceBehaviors> 
  7. <behaviors> 

 

THE END