It is easy to get a WCF service to run in a console app. I could not get a self-hosted WCF to work in a windows service. Probably too many security problems to deal with. To improve on the console-app service-hosting samples I make an AttachService method that runs on it's own thread like 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 aim is to execute this console app from a Windows service using Process class in the OnStart method. Thanks @Reed Copsey for the suggestion on WaitOne().