上一篇介紹了最簡單的方式來實現宿主和客戶端:直接引用契約和服務項目、采用硬編碼的方式,這次通過配置文件來定義終結點。剛接觸WCF時,直接編輯配置文件會讓人一頭霧水,所以還是使用直觀的方式——使用WCF編輯工具,這個工具可以通過“開始”→“Microsoft Visual Studio 2010”→“Microsoft Windows SDK Tools”→“服務配置編輯器”打開,也可以通過VS2010的IDE中“工具”→“WCF服務配置編輯器”打開。
宿主:
1、在之前的解決方案中添加一個Windows窗體應用程序WCFDemo.Host.WithConfig。
2、添加引用System.ServiceModel。
3、引用上一篇的契約和服務兩個項目。
4、為宿主項目添加應用程序配置文件,並編輯:
運行配置工具,打開宿主項目的配置文件,右擊樹形目錄的“服務”節點新建服務;

把Name屬性設置為我們之前寫的服務;

新建服務終結點,並設置A(Address)、B(Binding)、C(Contract)。設置的值和上一篇代碼里的一樣;

保存后可以查看配置文件。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="WCFDemo.Services.DemoService">
<endpoint address="http://localhost:5678/DemoService" binding="basicHttpBinding"
bindingConfiguration="" contract="WCFDemo.Contracts.IDemoService" />
</service>
</services>
</system.serviceModel>
</configuration>
5、在窗體放置兩個Button和一個Label,編寫代碼如下:
using System;
using System.Windows.Forms;
using System.ServiceModel;
using WCFDemo.Services;
namespace WCFDemo.Host.WithConfig
{
public partial class HostWithConfigForm : Form
{
public HostWithConfigForm()
{
InitializeComponent();
}
ServiceHost host;
private void button1_Click(object sender, EventArgs e)
{
host = new ServiceHost(typeof(DemoService));
host.Opened += delegate { label1.Text = "服務啟動"; };
host.Open();
}
private void button2_Click(object sender, EventArgs e)
{
if (host != null && host.State == CommunicationState.Opened)
{
host.Closed += delegate { label1.Text = "服務停止"; };
host.Close();
}
}
}
}
可以發現,和之前唯一不同就是少了添加服務終結點的代碼。運行帶配置的宿主程序,再運行之前的客戶端程序,可以正常通訊。接下來看一下使用配置文件的客戶端。
客戶端:
1、在之前的解決方案中添加一個Windows窗體應用程序WCFDemo.Client.WithConfig。
2、添加引用System.ServiceModel。
3、引用之前契約項目。
4、為客戶端項目添加應用程序配置文件,並編輯:
運行配置工具,打開客戶端項目的配置文件,右擊樹形目錄的“客戶端”→“終結點”節點新建客戶端終結點,並設置ABC和Name:

保存后可以查看配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<client>
<endpoint address="http://localhost:5678/DemoService" binding="basicHttpBinding"
bindingConfiguration="" contract="WCFDemo.Contracts.IDemoService"
name="DemoService" />
</client>
</system.serviceModel>
</configuration>
5、在窗體放置一個Button和一個DataGridView,並編寫代碼如下:
using System;
using System.Windows.Forms;
using System.ServiceModel;
using WCFDemo.Contracts;
namespace WCFDemo.Client.WithConfig
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (ChannelFactory<IDemoService> channelFactory = new ChannelFactory<IDemoService>("DemoService"))
{
dataGridView1.DataSource = channelFactory.CreateChannel().GetMonitorData();
}
}
}
}
代碼中ChannelFactory構造函數的參數和配置文件中的Name要一致。
現在,使用配置文件和不使用配置文件的宿主及客戶端已完成,兩個服務器和兩個客戶端之間都可通訊。看得出來,客戶端使用服務都是對某個終結點的,客戶端的ABC要和服務端一致。
目前為止,客戶端都是通過直接引用契約類庫來使用WCF服務的,很多時候客戶端無法直接引用契約類庫,這就需要服務端發布自己的契約,客戶端根據契約生成代理類。
如何實現,下一篇再說——簡短一點兒好。
