和传统的分布式通信框架一样,WCF本质上提供一个跨进程、跨机器以致跨网络的服务调用。其中主要包括契约(Contract),绑定(Binding),地址(Address)。
WCF的服务不能孤立地存在,需要寄宿于一个运行着的进程中,我们把承载WCF服务的进程称为宿主,为服务指定宿主的过程称为服务寄宿(Service Hosting)。在我们的计算服务应用中,采用了两种服务寄宿方式:通过自我寄宿(Self-Hosting)的方式创 建一个控制台应用作为服务的宿主(寄宿进程为Hosting.exe);通过IIS寄宿方式将服务寄宿于IIS中(寄宿进程为IIS的工作进行 W3wp.exe)。客户端通过另一个控制台应用模拟(进程为Client.exe)。下面主要是介绍自我寄宿方式创建服务宿主。
2:创建标准的第一个WCF程序。
首先创建一个空的解决方案:WCFCalculator
右键点击解决方案选择Add->New Project并选择Console Application模板并选择名为项目名为Host(服务器端)
同理:右键点击解决方案选择Add->New Project并选择Console Application模板并选择名为项目名为Client(客户端)
右击项目Host,添加WCF Service,命名为Calculator
添加后,产生Calculator.cs,ICalculator.cs 以及app.config三个文件。
在ICalculator.cs中写服务契约:
namespace Host
{
// NOTE: If you change the interface name "ICalculator" here, you must also update the reference to "ICalculator" in App.config.
[ServiceContract]
public interface ICalculator
{
[OperationContract]
double Add(double x, double y);//代表外部可以访问的服务
}
}
{
// NOTE: If you change the interface name "ICalculator" here, you must also update the reference to "ICalculator" in App.config.
[ServiceContract]
public interface ICalculator
{
[OperationContract]
double Add(double x, double y);//代表外部可以访问的服务
}
}
然后Calculator.cs:
namespace Host
{
// NOTE: If you change the class name "Calculator" here, you must also update the reference to "Calculator" in App.config.
public class Calculator : ICalculator
{
public double Add(double x,double y)
{
return x + y;
}
}
}