Search code examples
c#.net-4.0windows-servicesconsole-application

.NET console application as Windows service


I have console application and would like to run it as Windows service. VS2010 has project template which allow to attach console project and build Windows service. I would like to not add separated service project and if possible integrate service code into console application to keep console application as one project which could run as console application or as windows service if run for example from command line using switches.

Maybe someone could suggest class library or code snippet which could quickly and easily transform c# console application to service?


Solution

  • I usually use the following techinque to run the same app as a console application or as a service:

    using System.ServiceProcess
    
    public static class Program
    {
        #region Nested classes to support running as service
        public const string ServiceName = "MyService";
    
        public class Service : ServiceBase
        {
            public Service()
            {
                ServiceName = Program.ServiceName;
            }
    
            protected override void OnStart(string[] args)
            {
                Program.Start(args);
            }
    
            protected override void OnStop()
            {
                Program.Stop();
            }
        }
        #endregion
        
        static void Main(string[] args)
        {
            if (!Environment.UserInteractive)
                // running as service
                using (var service = new Service())
                    ServiceBase.Run(service);
            else
            {
                // running as console app
                Start(args);
    
                Console.WriteLine("Press any key to stop...");
                Console.ReadKey(true);
    
                Stop();
            }
        }
        
        private static void Start(string[] args)
        {
            // onstart code here
        }
    
        private static void Stop()
        {
            // onstop code here
        }
    }
    

    Environment.UserInteractive is normally true for console app and false for a service. Techically, it is possible to run a service in user-interactive mode, so you could check a command-line switch instead.