WCF 學習總結1 -- 簡單例項
從VS2005推出WCF以來,WCF逐步取代了Remoting, WebService成為.NET上分散式程式的主要技術。WCF統一的模型整合了以往的 WebService、Remoting、MSMQ 等技術,讓分散式開發變得更加簡單,方便,快捷。
(上圖選自《Programming WCF Services》)
WCF基本概念(ABC): 1.地址(Address):決定服務的地址;2.繫結(Binding):決定服務的細節;3.契約(Contract):服務的定義(抽象),決定訊息結構的定義。
WCF的釋出:WCF服務的釋出可以有幾種形式: IIS, Windows Service, Self-Host(可以是Console程式也可以是Winform程式)。
WCF的工具: Windows Communication Foundation 工具
簡單例項-1: 內建AppDomain (無配置)
1. Service1.cs
namespace WCFStudy1 { [ServiceContract] public interface IService1 { [OperationContract] string SendMessage(string clientInput); } public class Service1 : IService1 { #region IService1 Members public string SendMessage(string clientInput) { return string.Format("Server Get Message: {0}", clientInput); } #endregion } }
2. Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace WCFStudy1 { class Program { static void Main(string[] args) { // 建立一個獨立AppDomain作為服務端。 AppDomain.CreateDomain("Server1").DoCallBack(delegate { ServiceHost host = new ServiceHost(typeof(Service1)); host.AddServiceEndpoint(typeof(IService1), //契約(C) new BasicHttpBinding(), //繫結(B) "http://localhost:9999/myservice"); //地址(A) host.Open(); }); // 下面是客戶端 ChannelFactory<IService1> factory = new ChannelFactory<IService1>( new BasicHttpBinding(), "http://localhost:9999/myservice"); IService1 client = factory.CreateChannel(); var reply = client.SendMessage("Hello WCF"); Console.WriteLine(reply); Console.Read(); } } }
如圖所示:
簡單例項-2: 建立 Console Self-Host
WcfServiceLib - 服務契約的實現; *ConsoleHost工程 – Wcf宿主; *ConsoleClient工程 - Wcf客戶端
- 建立WcfServiceLib工程(選WCF Service Library工程模板: VS為我們自動新增一個IService1.cs和Service1.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using WcfServiceLib;
namespace WCFStudy2ConsoleHost
{
class Program
{
static void Main(string[] args)
{
using(var host = new ServiceHost(typeof(Service1)))
{
host.Open();
Console.WriteLine("Service start.");
Console.Read();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WCFStudy2ConsoleClient
{
class Program
{
static void Main(string[] args)
{
MyWcfSvc.Service1Client client = new MyWcfSvc.Service1Client();
var result = client.GetData(123);
Console.WriteLine(result);
Console.Read();
}
}
}
執行結果:
由於ServiceHost例項是被建立在應用程式域中,必須保證宿主程序在呼叫服務期間不會被關閉,因此利用Console.Read()來阻塞程序,以使得控制檯應用程式能夠一直執行,直到人為關閉應用程式。
簡單例項-3: 建立 Winform Self-Host
Winform的Self-Host和ConsoleHost類似,先新增 WcfServiceLib 工程引用,將 WcfServiceLib 裡的App.config 移到 Winform 工程裡。加上啟動Service的程式碼就OK了!
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private ServiceHost host = null;
// 開啟服務端
private void btnStart_Click(object sender, EventArgs e)
{
try
{
if (host != null)
host.Close();
host = new ServiceHost(typeof(WcfServiceLib.Service1));
host.Open();
this.textBox1.Text = "Server Opened!";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
if (host != null)
host.Close();
}
}
// 關閉服務端
private void btnStop_Click(object sender, EventArgs e)
{
if (host != null)
{
host.Close();
this.textBox1.Text += "Server Closed!";
}
}
}
在Winform中,不要使用 using(...) 程式碼塊,這將導致在Button方法結束後自動銷燬Host物件而關閉服務。
簡單例項-4: 建立 Windows Service Host
Windows Services宿主便於管理者方便地啟動或停止服務,且在服務出現故障之後,能夠重新啟動服務。還可以通過Service Control Manager(服務控制管理器),將服務設定為自動啟動方式,省去了服務的管理工作。此外,Windows Services自身還提供了一定的安全性以及檢測機制和日誌機制。
1. 建立Windows Service工程
2. 引用 WcfServiceLib 工程,新增 App.config (和前面Host新增的App.config一樣)
3. 重寫 WindowsService 類的 OnStart 和 OnStop 方法
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
private ServiceHost host = null;
protected override void OnStart(string[] args)
{
if (host != null)
host.Close();
host = new ServiceHost(typeof(WcfServiceLib.Service1));
host.Open();
}
protected override void OnStop()
{
if (host != null)
host.Close();
}
}
4. 建立Service的安裝類:在WindowsService 類的設計介面上右擊選擇 [Add Installer]
修改 serviceProcessInstaller 的 Account 屬性 (預設為User) 改為 LocalSystem
通過在Visual Studio的 [Command Prompt] (命令列)模式下通過 InstallUtil 工具安裝 Windows服務: InstallUtil [絕對路徑]/WCFStudy2WindowsServiceHost.exe (安裝成功之後,使用Services.msc檢視服務)
簡單例項-5: 建立 IIS Host
最簡單的就是直接建立一個 WCF Service Application 就OK了。
以上所有工程的關係圖如下: