Itβs easy to get a WCF service to run in a console application. I could not get standalone WCF to work in a windows service. There are probably too many security issues. To improve hosting selection for the console application, I create an AttachService method that runs its own thread on it, similar to this.
public static AutoResetEvent manualReset; // Host the service within this EXE console application. public static void Main() { manualReset = new AutoResetEvent(false); ThreadPool.QueueUserWorkItem(AttachService); //put Set() signal in your logic to stop the service when needed //Example: ConsoleKeyInfo key; do { key = Console.ReadKey(true); } while (key.Key != ConsoleKey.Enter); manualReset.Set(); } static void AttachService(Object stateInfo) { // Create a ServiceHost for the CalculatorService type. using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), new Uri("net.tcp://localhost:9000/servicemodelsamples/service"))) { // Open the ServiceHost to create listeners and start listening for messages. serviceHost.Open(); // The service can now be accessed. //Prevent thread from exiting manualReset.WaitOne(); //wait for a signal to exit //manualReset.Set(); } }
My goal is to run this console application from a Windows service using the Process class in the OnStart method. Thanks @Reed Copsey for the WaitOne () suggestion.
source share