WCF——1.2 WCF服务、控制台宿主、控制台客户端

来源:互联网 发布:软件安全测试培训 编辑:程序博客网 时间:2024/05/16 09:55

原文:点击打开链接

自己对照做的demo: 点击打开链接


SelfHostConsole_overview

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

  1. 创建WcfServiceLib工程(选WCF Service Library工程模板: VS为我们自动添加一个IService1.cs和Service1.cs)
    SelfHostConsole_servicelib
  2. Host工程里引用WcfServiceLib工程
    SelfHostConsole_hostRef
  3. 将WcfServiceLib里App.config移动到ConsoleHost工程里,删掉Lib工程里的App.config
    SelfHostConsole_appconfig
  4. 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. }  
  5. 运行 ConsoleHost工程 bin/debug 下面的 exe(这一步是为了生成客户端代理,需要启动Host) 
  6. 在Client工程里通过添加 Service References,生成客户端Proxy,关闭exe
    SelfHostConsole_clientproxy
  7. 在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. }  
  8. F5 运行Solution里的Host, 再右击Client工程选Debug的Start new instance方式,运行Client

    运行结果:

    SelfHostConsole_runtime

     

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

原创粉丝点击