Hacker News new | past | comments | ask | show | jobs | submit login

I've just rolled out a service using TopShelf having not used it previously. It really does simplify things. The best bit for me is being able to just hit F5 and having the thing run as a console application. No need to manually attach to processes for debugging.



This technique lets you debug your service as if it were a console app - just pass in -a on the command line.

In your Main method:

            if (args.Length > 0 && args[0] == "-a")
            {
                // Running as an application
                MyService ms = new MyService();
                ms.DoStart();
                Console.WriteLine("Press Enter to Stop");
                Console.ReadLine();
                ms.DoStop();
            } else {
                // Running as a service
                ServiceBase[] servicesToRun = { new MyService() };
                ServiceBase.Run(servicesToRun);
            }
And in the MyService class that derives from ServiceBase:

        protected override void OnStart(string[] args)
        {
            DoStart();
        }

        protected override void OnStop()
        {
            DoStop();
        }

        internal void DoStart()
        {
            // Start your service thread here
        }

        internal void DoStop()
        {
            // Tell your service thread to stop here
        }


I use something similar to debug a WCF project:

  private static void Main()
  {
    var serviceHandler = new ServiceHandler();

    if (Environment.UserInteractive)
    {
      serviceHandler.OnStart(null);
      Console.WriteLine("Service started! Press <ENTER> to terminate service.");
      Console.ReadLine();
      serviceHandler.OnStop();
      Console.WriteLine("Service stopped!");
      return;
    }
    
    Run(serviceHandler);
  }


I normally use this (simple) technique: http://stackoverflow.com/a/126016




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: