WPF——自托管 WCF

WPF - Self hosting WCF

我正在使用此示例创建一个自托管 WCF 应用程序 (.NET 4.5): https://msdn.microsoft.com/en-us/library/ms731758%28v=vs.110%29.aspx

我已经成功地使用它创建了一个控制台应用程序。

但我现在正尝试在全新的 WPF 应用程序中使用相同的代码。

我唯一改变的是删除:

host.Close();

所以应用 运行 连接正常打开。

但是当我使用 WCF 测试客户端测试 WPF 应用程序时,returns 出现错误:

Error: Cannot obtain Metadata from http://localhost:8080/hello If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address. For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange Error URI: http://localhost:8080/hello Metadata contains a reference that cannot be resolved: 'http://localhost:8080/hello'. There was no endpoint listening at http://localhost:8080/hello that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details. Unable to connect to the remote server No connection could be made because the target machine actively refused it 127.0.0.1:8080HTTP GET Error URI: http://localhost:8080/hello There was an error downloading 'http://localhost:8080/hello'. Unable to connect to the remote server No connection could be made because the target machine actively refused it 127.0.0.1:8080

如果我在以下位置设置断点:

host.Open(); 

是运行,所以运行服务应该没问题吧?

我的 WPF 应用程序与控制台应用程序有什么区别会导致此问题。在这两种情况下,Visual studio 都是 运行 管理员。

主要代码:

 using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
        {
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            host.Description.Behaviors.Add(smb);

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

MSDN 示例中的代码包含对 Console.ReadLine() 的调用,这会阻止应用程序退出实例化和打开 ServiceHost 实例的 using 块。

当您将代码移动到 WPF 应用程序时,通过保留 using 块,但不阻止代码的执行退出块(您不想这样做,因为它是一个 GUI)你实际上是在创建一个服务主机,然后立即处理它。

您将需要 bootstrap 您的 ServiceHost 在 using 块之外,并在适合您的应用程序时手动处理它。