(3)在Main方法中添加下面的代码:
{
Type serviceType = typeof(Calculator);
using (ServiceHost host = new ServiceHost(serviceType))
{
}
}
第一行代码得到一个类型引用,这个类型就是具体实现WCF服务的那个类,也是我们将要在宿主程序中运行的类。
using语句用来对ServiceHost实例进行初始化,在作用域结束时ServiceHost的Dispose()会被自动调用。
(4)在using语句内部,我们先启动ServiceHost,然后通过等待用户输入的方式来阻止应用程序退出。
(5)下面是完整的代码,新增的代码加亮显示。
{
class Program
{
static void Main(string[] args)
{
Type serviceType = typeof(Calculator);
using (ServiceHost host = new ServiceHost(serviceType))
{
host.Open();
Console.WriteLine("The calculator service is available.");
Console.ReadKey();
}
}
}
}
(6)选择File | Save All菜单项。
(7)在进入下一个任务之前请确保解决方案能够编译通过(按CTRL+Shift+B快捷键)。
3.配置服务
配置WCF服务的过程非常直接。配置选项对服务在运行的时候的行为进行控制。虽然服务的配置选项有许多,但在这个任务中我们只对服务的一些非常基本的行为进行配置。
(1)在Solution Explorer中选中Host项目,然后在主菜单中选择Project | Add New Item菜单项。
(2)在Project | Add New Item对话框中选择Application Configuration File模板,如图3所示。

图3 Add New Item对话框
(3)不要修改文件名,新的配置文件的文件名仍然是app.config。
(4)单击Add按钮。
(5)用下面的XML代码替换掉新添加的app.config文件中的所有内容。下面对配置设定做了一个简单的介绍。
<configuration>
<system.serviceModel>
<services>
<service name="DerivativesCalculatorService.Calculator"
behaviorConfiguration="metadataBehavior">
<endpoint
address="CalculatorService"
binding="basicHttpBinding"
contract="DerivativesCalculatorService.IDerivativesCalculator"/>
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/Derivatives/" />
<add baseAddress="net.tcp://localhost:8010/Derivatives/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="metadataBehavior">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
WCF配置文件的结构
•
•
•
•
•
•
•
(6)选择File | Save All菜单项。
(7)确保解决方案能够正常编译(选择Build | Build Solution菜单项)。