Search code examples
wcf

Not to close the WCF service host from key stroke


We have created a service host console application that needs users key stroke to close it and the code snippet is as follows:

            ........
            host.Open();                

            Console.WriteLine($"The service is ready {host.Description.Endpoints?.FirstOrDefault()?.Address.Uri.ToString()}");
            
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.WriteLine();
            Console.ReadLine();
            Console.WriteLine("<ENTER> pressed, about to Shutdown Service Host ...");
            host.Close();
            Console.WriteLine("Service Host is closed");
            .......

I would like to remove user intervention to close the host and keep it opened. Will commenting host.Close() line confirm that it is still opened ?

-------------------------------UPDATE --------------------------------------

My previous post probably was not clear enough. I am looking forward to a machine to machine interaction to start and stop WCF Service Host instead of the human to machine interaction. Our current solution is based on the following:

How to: Host a WCF service in a managed app

The problem we are facing is that the .exe based on the above solution shuts down right after is started the channel at a certain end-point address. It is obvious that the ENTER is pressed somehow

Is the following can be probable solution to what we are facing ?

How to: Host a WCF Service in a Managed Windows Service


Solution

  • You just need to remove host.Close(). The host.Close() method will make the communication object transition from its current state to the closed state. For more information about ServiceHost Class, you can refer to this link.

    UPDATE:

    As long as host.Close() is not run, the WCF service will remain open under normal circumstances. If the WCF service is hosted in a Windows Service, we can start and close the WCF service by running the Windows service or stopping the Windows service.

    WCF can also be hosted in IIS. The WCF service hosted in IIS is like a Web application. As long as the site is in the Start state, the WCF service will always run.

    For more information about "Host a WCF Service in IIS", you can refer to this link.