Trick for debugging windows service

Debugging a windows service can be slow and cumbersome. You will have to install the service, start the service through the services control manager, attaching to the thread etc.

One nice thrick to debug a windows service is to adjust the program main method with the following code, it will detect if you start the service manually and present a console direct away:

/// 
        /// The main entry point for the application.
        /// 
        static void Main(string[] args)
        {
            Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var servicesToRun = new ServiceBase[] { new AdControllerService() };

            if (Environment.UserInteractive)
            {
                // Start for debugging
                var type = typeof(ServiceBase);
                const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
                var method = type.GetMethod("OnStart", flags);
                foreach (var service in servicesToRun)
                {
                    method.Invoke(service, new object[] { args });
                }

                Console.WriteLine("Service is started. Press any key to exit");
                Console.ReadKey();

                var stopMethod = type.GetMethod("OnStop", flags);
                foreach (var service in servicesToRun)
                {
                    stopMethod.Invoke(service, new object[] { });
                }
            }
            else
            {
                // Startup as service. 
                ServiceBase.Run(servicesToRun);
            }        
        }

You will have to change the output type of your project from Class Library to Console Application

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!