首页 / 软件开发 / WCF / Learn WCF (4)--学会使用配置文件
Learn WCF (4)--学会使用配置文件2010-09-10 博客园 GWPBrian无论是Web应用程序还是Win应用程序,我们都会经常用到配置文件。WCF作为分布式开发的基础框架,在定义服务以及定义消费服务的客户端时,都使用了配置文件的方法。配置文件的重要性和实用性是大家所熟知的,它可以给我们WCF开发的灵活性上带来很大的提高。下面说说我学习使用配置文件的所得。WCF的配置使用.NET Framework的System.Configuration配置系统。在Visual Studio中配置一个WCF服务时,如果是自托管宿主或Windows Services宿主,则配置文件为App.confing,如果是IIS宿主,则配置文件为Web.config。先来看看简单的system.ServiceModel结构<system.ServiceModel>
<services>
<service>
<endpoint/>
</service>
</services>
<bindings>
<!—定义一个或多个系统提供的binding元素,例如<basicHttpBinding> -->
<!—也可以是自定义的binding元素,如<customBinding>. -->
<binding>
<!—例如<BasicHttpBinding>元素. -->
</binding>
</bindings>
<behaviors>
<!—一个或多个系统提供的behavior元素. -->
<behavior>
<!—例如<throttling>元素. -->
</behavior>
</behaviors>
</system.ServiceModel>
(1)<services>服务是在配置文件的 services 节中定义的。每个服务都有自己的 service 配置节。在Service中定义特定服务的address,binding,contract(也就是传说中重要的ABC)。 <services>
<service name="WCFStudent.WCFStudentText" behaviorConfiguration="ServiceBehavior">
<endpoint address="" binding="wsHttpBinding" contract="WCFStudent.IStuServiceContract"></endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<!--一个Service中可以有多个endpoint,这样就可以同时定制多个服务。如果address值为空,那么endpoint的地址就是默认的基地址(Base Address)。那么则需要在host中声明Base Address-->
(2)<bindings>此节包含标准绑定和自定义绑定的集合。每一项都是一个可由其唯一 name 进行标识的 binding 元素。服务通过用 name 与绑定进行链接来使用绑定。个人感觉比较常用的是<basicHttpBinding>,<basicHttpBinding>等。由于属性比较多,在这里就不一一说明了。<bindings>
<basicHttpBinding>
<binding name="IStuServiceContract" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
</basicHttpBinding>
</bindings>
<!--相应属性的设置大家可以参看MSDN.
http://msdn.microsoft.com/zh-cn/library/ms731361.aspx-->