2015-01-16 154 views
0

我有一個託管WCF服務的控制檯應用程序。現在我配置應用程序以下列方式運行:帶多個服務的WCF控制檯應用程序

// within my program class 
class Program 
{ 
    static void Main(string[] args) 
    { 
     // retrieve the current URL configuration 
     Uri baseAddress = new Uri(ConfigurationManager.AppSettings["Uri"]); 

然後我開始WebServiceHost的一個新的實例來承載我的WCF REST服務

using (WebServiceHost host = new WebServiceHost(typeof(MonitorService), baseAddress)) 
{ 
    ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof (IMonitorService), new WebHttpBinding(), ""); 
    ServiceDebugBehavior stp = host.Description.Behaviors.Find<ServiceDebugBehavior>(); 
    stp.HttpHelpPageEnabled = false; 

    host.Open(); 

    Console.WriteLine("The service is ready at {0}", baseAddress); 
    Console.WriteLine("Press <Enter> to stop the service."); 
    Console.ReadLine(); 

    // Close the ServiceHost. 
    host.Close(); 
} 

到目前爲止,除了現在好了我想出了具有以下結構主辦了兩屆WCF服務的需求

http://localhost:[port]/MonitorServicehttp://localhost:[port]/ManagementService

我可以添加新的服務端點並通過使用不同的合同區分兩個端點嗎?如果是,這兩個合同的實現應該駐留在同一個類MonitorService中,因爲它是WebServiceHost使用的類?

回答

1

是的,您可以在單一控制檯應用程序中託管多項服務。您可以爲多個服務創建多個主機。您可以使用以下通用方法爲給定服務啓動主機。

/// <summary> 
    /// This method creates a service host for a given base address and service and interface type 
    /// </summary> 
    /// <typeparam name="T">Service type</typeparam> 
    /// <typeparam name="K">Service contract type</typeparam> 
    /// <param name="baseAddress">Base address of WCF service</param> 
    private static void StartServiceHost<T,K>(Uri baseAddress) where T:class 
    { 
     using (WebServiceHost host = new WebServiceHost(typeof(T), baseAddress)) 
     { 
      ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(K), new WebHttpBinding(), ""); 
      ServiceDebugBehavior stp = host.Description.Behaviors.Find<ServiceDebugBehavior>(); 
      stp.HttpHelpPageEnabled = false; 

      host.Open(); 

      Console.WriteLine("The service is ready at {0}", baseAddress); 
      Console.WriteLine("Press <Enter> to stop the service."); 
      Console.ReadLine(); 

      // Close the ServiceHost. 
      host.Close(); 
     } 
    } 
+0

所以實際上我需要啓動多個服務主機,每個服務一個,並編寫一個機制,以便在關閉控制檯應用程序時全部處理。謝謝 – Raffaeu

相關問題