d199224 d199224 - 2 months ago 33
C# Question

Hosting WCF Service in WPF Application

I'm trying to host a WCF service inside a WPF application but I'm unable to do so.

Here is the code I implemented:

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


Everything looks ok and runs fine but the service does not start.

Anyone have an idea of what my problem may be?

Thanks

Tim Tim
Answer

The most likely issue is that you've wrapped the creation and opening of the ServiceHost in a using statement. Once that using statement finishes (and it's not clear from your posted code where it does), the ServiceHost instance will be closed.

In other words, if you close the using block right after host.Open(); like this:

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

The host will be closed and your application will not be able to receive requests. Generally you'll want to open the host on application start (or perhaps on a given event), and then close it once the application exits.

Comments