WCF服務(wù)宿主程序正確實(shí)現(xiàn)方法解析
WCF開(kāi)發(fā)工具是微軟公司研發(fā)的一種功能強(qiáng)大的開(kāi)發(fā)插件,是一個(gè).NET Framework 3.5的重要組成部分。我們今天將會(huì)通過(guò)這篇文章中介紹的內(nèi)容充分的了解到有關(guān)WCF服務(wù)宿主程序的實(shí)現(xiàn)方法。#t#
(1)在類(lèi)文件中,添加using語(yǔ)句來(lái)導(dǎo)入下面的名字空間:
·System.ServiceModel
·System.Configuration
·DerivativesCalculatorService
(2)代碼看起來(lái)應(yīng)該如下所示:
- 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服務(wù)宿主程序的代碼得到一個(gè)類(lèi)型引用,這個(gè)類(lèi)型就是具體實(shí)現(xiàn)WCF服務(wù)的那個(gè)類(lèi),也是我們將要在宿主程序中運(yùn)行的類(lèi)。
using語(yǔ)句用來(lái)對(duì)ServiceHost實(shí)例進(jìn)行初始化,在作用域結(jié)束時(shí)ServiceHost的Dispose()會(huì)被自動(dòng)調(diào)用。
(4)在using語(yǔ)句內(nèi)部,我們先啟動(dòng)ServiceHost,然后通過(guò)等待用戶(hù)輸入的方式來(lái)阻止應(yīng)用程序退出。
(5)下面是完整的WCF服務(wù)宿主程序代碼,新增的代碼加亮顯示。
- 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菜單項(xiàng)。
(7)在進(jìn)入下一個(gè)任務(wù)之前請(qǐng)確保解決方案能夠編譯通過(guò)(按CTRL+Shift+B快捷鍵)。
以上就是我們?yōu)榇蠹医榻B的有關(guān)WCF服務(wù)宿主程序的相關(guān)內(nèi)容。