Start Windows service in a console window

I spend a lot of time writing windows services. If I had to install every one I worked on locally, my box would be terribly tired and a mess to boot.

A friend showed me a trick for starting the service in a console window. Use this code in your Main. You may have to add the string[] args parameter.

static void Main(string[] args)
        {
	   //Start IOC Container Structuremap
           //http://structuremap.net/structuremap/
            _bootStrapper = new IocContainerBootstrapper();
            _bootStrapper.BootstrapStructureMap();

            //This configurator starts up log4net
            XmlConfigurator.Configure();

            Log.DebugFormat("The SweetService service bootstrapped '{0}':"
              , ObjectFactory.WhatDoIHave());

            //Add '/console' to start options > Command Line Arguments in
            //your project properties
	    //to get the service to start in console for debugging
            if (args.Length > 0 && args[0] == "/console")
            {
      Log.Debug("Starting this sweet service in Console mode for debugging");
               SweetService myService = new SweetService();
                myService.OnStart(args);
                Console.ReadKey();
            }
            else
            {
                ServiceBase[] servicesToRun = new ServiceBase[]
                  { new LabImportEngine() };
                Run(servicesToRun);
            }
        }

Put  ‘/console’ in your Start Options / Command line arguments in your visual studio project properties and set your project type to Console Application.

When you start the project now in a debugger, you will get a lovely console window with all your log4net output and you never had to install the service to work on it.

For this example, I am using log4net and I am using a colored console appender.  That makes the output in the console window great.

Enjoy,

Jim

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.