/* * Windows Service Install, Start, Stop, Query, Delete Commands: * ============================================================= * sc create "Nano.Demo.SelfHost.WindowsService" binPath= "C:\PathToExecutable\Nano.Demo.SelfHost.WindowsService.exe ApplicationName Nano.Demo.SelfHost.WindowsService Uri http://localhost:8686" start= auto * sc start "Nano.Demo.SelfHost.WindowsService" * sc stop "Nano.Demo.SelfHost.WindowsService" * sc query "Nano.Demo.SelfHost.WindowsService" * sc delete "Nano.Demo.SelfHost.WindowsService" */ private static void Main(string[] args) { var applicationName = args.GetArgumentValue("ServiceName") ?? args.GetArgumentValue("ApplicationName") ?? AppDomain.CurrentDomain.FriendlyName; var url = args.GetArgumentValue("Url") ?? args.GetArgumentValue("Uri") ?? "http://localhost:4545"; WindowsServiceHelper.Start(applicationName, () => Startup.Start(url, applicationName), Startup.Stop); }
/// <summary> /// Starts the Windows Service. /// </summary> /// <param name="serviceName">Service name.</param> /// <param name="onStart">Function to execute on start of Windows Service.</param> /// <param name="onStop">Function to execute on stop of Windows Service.</param> public static void Start(string serviceName, Action onStart, Action onStop) { if (!Environment.UserInteractive) { // Running as a Windows Service using (var service = new WindowsServiceHelper(serviceName, onStart, onStop)) { System.ServiceProcess.ServiceBase.Run(service); } } else { var exitEvent = new ManualResetEvent(false); // Running as Console application Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; exitEvent.Set(); }; try { onStart(); } catch (Exception e) { Console.WriteLine("A fatal error occurred!" + Environment.NewLine); Console.WriteLine(e); throw; } Console.WriteLine("Press Ctrl+C to exit."); exitEvent.WaitOne(); onStop(); } }