WCF 学习总结1 -- 简单实例

从VS2005推出WCF以来,WCF逐步取代了Remoting, WebService成为.NET上分布式程序的主要技术。WCF统一的模型整合了以往的 WebService、Remoting、MSMQ 等技术,让分布式开发变得更加简单,方便,快捷。

wcf_host_architecture 

(上图选自《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

 

[c-sharp] view plaincopy
 
  1. namespace WCFStudy1  
  2. {  
  3.     [ServiceContract]  
  4.     public interface IService1  
  5.     {  
  6.         [OperationContract]  
  7.         string SendMessage(string clientInput);  
  8.     }  
  9.     public class Service1 : IService1  
  10.     {  
  11.         #region IService1 Members  
  12.         public string SendMessage(string clientInput)  
  13.         {  
  14.             return string.Format("Server Get Message: {0}", clientInput);  
  15.         }  
  16.         #endregion  
  17.     }  
  18. }  

 

2. Program.cs

 

[c-sharp] view plaincopy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.ServiceModel;  
  6. namespace WCFStudy1  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             // 创建一个独立AppDomain作为服务端。  
  13.             AppDomain.CreateDomain("Server1").DoCallBack(delegate  
  14.             {  
  15.                 ServiceHost host = new ServiceHost(typeof(Service1));  
  16.                 host.AddServiceEndpoint(typeof(IService1),                  //契约(C)  
  17.                                         new BasicHttpBinding(),             //绑定(B)  
  18.                                         "http://localhost:9999/myservice"); //地址(A)  
  19.                 host.Open();  
  20.             });  
  21.             // 下面是客户端  
  22.             ChannelFactory<IService1> factory = new ChannelFactory<IService1>(  
  23.                 new BasicHttpBinding(),  
  24.                 "http://localhost:9999/myservice");  
  25.             IService1 client = factory.CreateChannel();  
  26.             var reply = client.SendMessage("Hello WCF");  
  27.             Console.WriteLine(reply);  
  28.             Console.Read();  
  29.         }  
  30.     }  
  31. }  

 

 

如图所示:


简单实例-2: 创建 Console Self-Host

SelfHostConsole_overview

WcfServiceLib - 服务契约的实现; *ConsoleHost工程 – Wcf宿主; *ConsoleClient工程 - Wcf客户端

    1. 创建WcfServiceLib工程(选WCF Service Library工程模板: VS为我们自动添加一个IService1.cs和Service1.cs)


SelfHostConsole_servicelib

    1. Host工程里引用WcfServiceLib工程


SelfHostConsole_hostRef

    1. 将WcfServiceLib里App.config移动到ConsoleHost工程里,删掉Lib工程里的App.config


SelfHostConsole_appconfig

    1. Host工程的Program.cs添加下面的代码,右击Builder工程

 

[c-sharp] view plaincopy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.ServiceModel;  
  6. using WcfServiceLib;  
  7. namespace WCFStudy2ConsoleHost  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             using(var host = new ServiceHost(typeof(Service1)))  
  14.             {  
  15.                 host.Open();  
  16.                 Console.WriteLine("Service start.");  
  17.                 Console.Read();  
  18.             }  
  19.         }  
  20.     }  
  21. }  
    1. 运行 ConsoleHost工程 bin/debug 下面的 exe(这一步是为了生成客户端代理,需要启动Host) 
    2. 在Client工程里通过添加 Service References,生成客户端Proxy,关闭exe


SelfHostConsole_clientproxy

    1. 在Client工程的Program.cs里添加如下代码。

 

[c-sharp] view plaincopy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace WCFStudy2ConsoleClient  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             MyWcfSvc.Service1Client client = new MyWcfSvc.Service1Client();  
  12.             var result = client.GetData(123);  
  13.             Console.WriteLine(result);  
  14.             Console.Read();  
  15.         }  
  16.     }  
  17. }  
    1. F5 运行Solution里的Host, 再右击Client工程选Debug的Start new instance方式,运行Client

运行结果:

SelfHostConsole_runtime

 

由于ServiceHost实例是被创建在应用程序域中,必须保证宿主进程在调用服务期间不会被关闭,因此利用Console.Read()来阻塞进程,以使得控制台应用程序能够一直运行,直到人为关闭应用程序。


简单实例-3: 创建 Winform Self-Host

 

Winform的Self-Host和ConsoleHost类似,先添加 WcfServiceLib 工程引用,将 WcfServiceLib 里的App.config 移到 Winform 工程里。加上启动Service的代码就OK了!

 

[c-sharp] view plaincopy
 
  1. public partial class Form1 : Form  
  2. {  
  3.     public Form1()  
  4.     {  
  5.         InitializeComponent();  
  6.     }  
  7.     private ServiceHost host = null;  
  8.     // 开启服务端  
  9.     private void btnStart_Click(object sender, EventArgs e)  
  10.     {  
  11.         try  
  12.         {  
  13.             if (host != null)  
  14.                     host.Close();  
  15.             host = new ServiceHost(typeof(WcfServiceLib.Service1));  
  16.             host.Open();  
  17.             this.textBox1.Text = "Server Opened!";  
  18.         }  
  19.         catch (Exception ex)  
  20.         {  
  21.             MessageBox.Show(ex.ToString());  
  22.             if (host != null)  
  23.                 host.Close();  
  24.         }  
  25.     }  
  26.     // 关闭服务端  
  27.     private void btnStop_Click(object sender, EventArgs e)  
  28.     {  
  29.         if (host != null)  
  30.         {  
  31.             host.Close();  
  32.             this.textBox1.Text += "Server Closed!";  
  33.         }  
  34.     }  
  35. }  

 

 

在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 方法

 

  1. public partial class Service1 : ServiceBase  
  2. {  
  3.     public Service1()  
  4.     {  
  5.         InitializeComponent();  
  6.     }  
  7.     private ServiceHost host = null;  
  8.     protected override void OnStart(string[] args)  
  9.     {  
  10.         if (host != null)  
  11.             host.Close();  
  12.         host = new ServiceHost(typeof(WcfServiceLib.Service1));  
  13.         host.Open();  
  14.     }  
  15.     protected override void OnStop()  
  16.     {  
  17.         if (host != null)  
  18.             host.Close();  
  19.     }  
  20. }  

 

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了。

 

 

以上所有工程的关系图如下:

 

posted @ 2013-07-26 07:55  幕三少  阅读(1178)  评论(0编辑  收藏  举报