繁体   English   中英

具有多个服务的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

是否可以添加新的服务端点并通过使用不同的合同来区分两个端点? 如果是,则两个合同的实现应驻留在同一类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();
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM