Cannot start service from the command line or debugger

Change the Main method in Program class as follows:

    /// <summary>
    ///   The main entry point for the application.
    /// </summary>
    private static void Main()
    {
        var myService = new MyService();
        if (Environment.UserInteractive)
        {
            Console.WriteLine("Starting service...");
            myService.Start();
            Console.WriteLine("Service is running.");
            Console.WriteLine("Press any key to stop...");
            Console.ReadKey(true);
            Console.WriteLine("Stopping service...");
            myService.Stop();
            Console.WriteLine("Service stopped.");
        }
        else
        {
            var servicesToRun = new ServiceBase[] { myService };
            ServiceBase.Run(servicesToRun);
        }
    }

You have to add a Start method to your service class:

    public void Start()
    {
        OnStart(new string[0]);
    }

Change the output type of the project to ‘Console Application’ instead of ‘Windows Application’ in the ‘Application’ tab of the project properties. Now you can just press F5 to start debugging but you can still run the executable as a Windows Service.

Leave a Comment