技术开发 频道

如何在宿主程序中运行并保护WCF服务

  添加对服务项目的引用

  9. 在Solution Explorer中Host项目的References文件夹上按鼠标右键并选择Add Reference菜单项

  10. 在Projects选项卡中选择DerivativesCalculatorService,如图2所示。


图2 添加项目引用

  11. 单击OK按钮。

  实现服务宿主程序

  1. 在类文件中,添加using语句来导入下面的名字空间:

  ·System.ServiceModel

  ·System.Configuration

  ·DerivativesCalculatorService

  2. 代码看起来应该如下所示:

  using System;
  
using System.Collections.Generic;
  
using System.Linq;
  
using System.Text;
  
using System.Configuration;
  
using System.ServiceModel;
  
using DerivativesCalculatorService;
  
namespace Host
  {
  
class Program
  {
  
static void Main(string[] args)
  {
  }
  }
  }

   3. 在Main方法中添加下面的代码:

  static void Main(string[] args)
  {
  Type serviceType
= typeof(Calculator);
  
using (ServiceHost host = new ServiceHost(serviceType))
  {
  }
  }

  第一行代码得到一个类型引用,这个类型就是具体实现WCF服务的那个类,也是我们将要在宿主程序中运行的类。

  using语句用来对ServiceHost实例进行初始化,在作用域结束时ServiceHost的Dispose()会被自动调用。

  4. 在using语句内部,我们先启动ServiceHost,然后通过等待用户输入的方式来阻止应用程序退出。

  5. 下面是完整的代码,新增的代码加亮显示。

  namespace Host
  {
  
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快捷键)。

0
相关文章