在 WPF 应用程序中托管 WCF 服务

Hosting WCF Service in WPF Application

我正在尝试在 WPF 应用程序中托管 WCF 服务,但我无法这样做。

这是我实现的代码:

ServiceHost host = null;
using (host = new ServiceHost(typeof(WcfJsonTransferRestService.apiService)))
            {
                host.AddServiceEndpoint(typeof(WcfJsonTransferRestService.IApiService), new WebHttpBinding(), "http://localhost:3300/api/endpoint1");
                host.AddServiceEndpoint(typeof(WcfJsonTransferRestService.IApiService), new WebHttpBinding(), "http://localhost:3300/api/endpoint2");
                host.AddServiceEndpoint(typeof(WcfJsonTransferRestService.IApiService), new WebHttpBinding(), "http://localhost:3300/api/endpoint3");

host.Open();

一切正常,运行正常,但服务未启动。

有人知道我的问题是什么吗?

谢谢

最有可能的问题是您将 ServiceHost 的创建和打开包装在 using 语句中。一旦 using 语句完成(从您发布的代码中不清楚它在哪里),ServiceHost 实例将关闭。

换句话说,如果您在 host.Open(); 之后立即关闭 using 块,如下所示:

using (host = new ServiceHost(typeof(WcfJsonTransferRestService.apiService)))
{
    host.AddServiceEndpoint(typeof(WcfJsonTransferRestService.IApiService), new WebHttpBinding(), "http://localhost:3300/api/endpoint1");
    host.AddServiceEndpoint(typeof(WcfJsonTransferRestService.IApiService), new WebHttpBinding(), "http://localhost:3300/api/endpoint2");
    host.AddServiceEndpoint(typeof(WcfJsonTransferRestService.IApiService), new WebHttpBinding(), "http://localhost:3300/api/endpoint3");

    host.Open();
}

主机将关闭,您的应用程序将无法接收请求。通常,您会希望在应用程序启动时(或可能在给定事件时)打开主机,然后在应用程序退出时将其关闭。