【问题标题】:WCF Console Application with multiple Service具有多个服务的 WCF 控制台应用程序
【发布时间】:2015-01-16 11:47:13
【问题描述】:

我有一个托管 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 使用的那个?

【问题讨论】:

    标签: web-services wcf


    【解决方案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();
            }
        }
    

    【讨论】:

    • 所以实际上我需要启动多个服务主机,每个服务一个,并编写一种机制来在控制台应用程序关闭时一起处理。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 2016-02-11
    • 1970-01-01
    • 2014-08-01
    相关资源
    最近更新 更多