通过《WCF全面解析》来知识分享....感谢蒋金楠老师@Artech
一、VS中构建解决方案
Client一个控制台程序模拟的客户端,引用Service.ServiceModel.dll
Hosting是服务宿主的控制台程序,主要引用Service.Interface和和Service.ServiceModel.dll
Service用于定义服务类型的类库项目,引用Service.Interface
Service.Interfce用于定义服务契约的类库,主要引用了Service.ServiceModel.dll

二、创建服务契约

三、创建服务
在Service项目中实现ICalculator契约接口
CalculatorService类

四、通过自我寄宿的方式寄宿服务
服务寄宿:为服务指定一个宿主的过程。
WCF采用的是基于终结点(Endpoint)的通过手段。
终结点主要为:地址(Address)、绑定(Binding)、契约(Contract)
终结点易于记忆的公式:Endpoint=ABC

地址(Address):决定服务的位置,解决服务寻址的问题。
绑定(Binding):实现了通信的所有细节,包括网络传输、信息编码,以及其他为实现某种功能(比如传输安全、可靠信息传输、事务等)对消息进行的相应处理。
契约(Contract):对服务操作的抽象,也是对消息交换模式及消息结构的定义。
在Hosting项目中将CalculatorService服务寄宿在控制台程序中

上面的代码
WCF服务寄宿通过System.ServiceMdel.ServiceHost对象完成,是基于(type(CalculatorService))创建的,并添加了基于WSHttpBinding绑定的终结点,该终结点地址为http://127.0.0.1:3721/calculatorservice,并指定服务契约的类型为ICalculator。
ServiceMetadataBehavior是为ServiceHost添加的服务行为,并采用HTTP-GET的元数据获取方式,并且通过HttpUrl属性指定发布地址(http://127.0.0.1:3721/calculatorservice/metada)。服务成功寄宿后,可以通过该地址获取服务相关的元数据。
成功之后

在浏览器中查看元数据

WCF真正的开发中一般采用的是配置的方式进行终结点的添加和服务行为的定义
<configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="metadataBehavior"> <serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:3721/calculatorservice/metadata"/> </behavior> </serviceBehaviors> </behaviors> <services> <service name="Service.CalculatorService" behaviorConfiguration="metadataBehavior"> <endpoint address="http://127.0.0.1:3721/calculatorservice" binding="wsHttpBinding" contract="Service.Interface.ICalculator"/> </service> </services> </system.serviceModel> </configuration>
五、客户端调用服务
点击OK之后会出现一系列的服务调用代码和配置信息。
在Client项目中直接通过添加的代理类调用寄宿的CalculatorService服务
并执行相应的方法调用服务操作
控制台输出结果
还有几种服务调用方式:
1.通过ChannelFactory<ICalculator>,调用CreateChannel方法穿件服务代理对象完成服务调用
using(ChannelFactory<ICalculator> channelFactory=new ChannelFactory<ICaiculator>(new WSHttpBinding(),"http://127.0.0.1:3721/calculatorservice")) { ICalculator icalculator=channelFactory.CreateChannel(); Console.WriteLine("x + y = {2} when x = {0} and y={1}",1,2,icalculator.Add(1,2)); //相关服务操作 }
2.在配置文件中配置相应的信息,通过ChannelFactory<ICalculator> calculatorChannel=new ChannelFactory<ICalculator>("calculatorservice"),读取结点为calculatorservice的终结点
<configuration> <system.serviceModel> <client> <endpoint name="calculatorservice" address="http://127.0.0.1:3721/calculatorservice" binding="wsHttpBinding" contract="Service.Interface.ICalculator"/> </client> </system.serviceModel> </configuration>
六、通过IIS寄宿服务,没搞明白...- -!