WCF服務宿主程序正確實現方法解析
WCF開發工具是微軟公司研發的一種功能強大的開發插件,是一個.NET Framework 3.5的重要組成部分。我們今天將會通過這篇文章中介紹的內容充分的了解到有關WCF服務宿主程序的實現方法。#t#
(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服務宿主程序的代碼得到一個類型引用,這個類型就是具體實現WCF服務的那個類,也是我們將要在宿主程序中運行的類。
using語句用來對ServiceHost實例進行初始化,在作用域結束時ServiceHost的Dispose()會被自動調用。
(4)在using語句內部,我們先啟動ServiceHost,然后通過等待用戶輸入的方式來阻止應用程序退出。
(5)下面是完整的WCF服務宿主程序代碼,新增的代碼加亮顯示。
- 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快捷鍵)。
以上就是我們為大家介紹的有關WCF服務宿主程序的相關內容。