2015-01-16 117 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

相关问题