具有多个服务的 WCF 控制台应用程序

WCF Console Application with multiple Service

我有一个托管 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

我可以添加一个新的服务端点并使用不同的契约来区分这两个端点吗?如果是,这两个合同的实现应该驻留在同一个 class MonitorService 中,因为它是 WebServiceHost 使用的?

是的,您可以在单个控制台应用程序中托管多个服务。您可以为多个服务创建多个主机。您可以使用以下通用方法为给定服务启动主机。

    /// <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();
        }
    }