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

时间:2015-01-16 11:47:14

标签: web-services 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 个答案:

答案 0 :(得分: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();
        }
    }