WCF - 自託管



在此處,WCF 服務託管在控制檯應用程式中。下面給出了以適合的步驟按順序解釋整個過程的過程。

步驟 1 − 首先,讓我們建立 Service 合約及其實現。建立一個控制檯應用程式,將其命名為 MyCalculatorService。這是一個返回兩個數字相加的簡單服務。

Wcf Hosting Services Self 1

步驟 2 − 現在,右鍵單擊解決方案資源管理器中的引用並單擊新增引用。將開啟以下視窗;向專案新增 System.ServiceModel 引用。

Wcf Hosting Services Self 2

步驟 3 − 建立一個 ISimpleCalculator 介面,向類新增 ServiceContract 和 OperationContract 屬性,如下所示。你將在後面的會話中更多地瞭解這些合約。這些合約將向外部世界公開方法以使用此服務。

步驟 4 − 此檔案背後的程式碼如下 −

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace MyCalculatorWCFService {
   [ServiceContract()]
   Public interface ISimpleCalculator {
      [OperationContract()]
      int Add(int num1, int num2);
   }
}

步驟 5 − MyCalculatorService 是 IMyCalculatorService 介面的實現類,如下所示。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyCalculatorWCFService {
   Class SimpleCalculator : ISimpleCalculator {
      Public int Add(int num1, int num2) {
         return num1 + num2;
      }
   }
}

步驟 6 − 現在,我們已經準備好服務。讓我們著手實現託管過程。建立一個新的控制檯應用程式,將其命名為“MyCalculatorWCFServiceHost”。

Wcf Hosting Services Self 5

步驟 7 − 新增 system.servicemodel 和專案 MyCalculatorWCFService 的引用。

Wcf Hosting Services 6

其背後的程式碼如下 −

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyCalculatorWCFService;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace MyCalculatorWCFServiceHost {
   class Program {
      static void Main(string[] args) {
         //Create a URI to serve as the base address
         UrihttpUrl = newUri("https://:8090/MyCalculatorWCFService/SimpleCalculator");
         
         //Create ServiceHost
         ServiceHost host = newServiceHost(typeof(MyCalculatorWCFService.ISimpleCalculator), httpUrl);
         
         //Add a service endpoint
         host.AddServiceEndpoint(typeof(MyCalculatorWCFService.ISimpleCal culator), newWSHttpBinding(), "");
         
         //Enable metadata exchange
         ServiceMetadataBehaviorsmb = newServiceMetadataBehavior();
         smb.HttpGetEnabled = true;
         host.Description.Behaviors.Add(smb);

         //Start the Service
         host.Open();
         Console.WriteLine("Service is host at " + DateTime.Now.ToString());
         Console.WriteLine("Host is running... Press  key to stop");
         Console.ReadLine();
      }
   }
}
Wcf Hosting Services Self 8
廣告資訊