Running a Windows Service as a Console Application

Edit: Nowadays I would recommend TopShelf. It provides a simple framework for a Windows Service that's easy to debug, install, uninstall, etc.

If you have ever built a Windows Service then trying to debug it can be a problem, having to attach the debugger to a running process is not ideal and I like having the ability to just click "play".

Therefore, with a few changes to a Windows Service, it can be set to run as a console application within Visual Studio for debugging but is actually a Windows Service.

For this to work I am assuming a single service within the same process, if multiple services exist then a different solution will be needed

The Steps

Console Application

    ' The main entry point for the process
    <MTAThread()> _
    <System.Diagnostics.DebuggerNonUserCode()> _
    Shared Sub Main()
        Dim ServicesToRun() As System.ServiceProcess.ServiceBase

        ' More than one NT Service may run within the same process. To add
        ' another service to this process, change the following line to
        ' create a second service object. For example,
        '   ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}
        ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1}

    End Sub

In the modified code I am doing a few key things:

  1. Creating the single service:

    Dim serviceToRun As Service1 = New Service1

    in place of the line below that creates an array with one instance:

    ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1}
  2. Added an if statement based on "Environment.UserInteractive" that will be true for when running in Visual Studio.

    If Environment.UserInteractive Then
  3. If it's within Visual Studio then the code just starts the service by calling the start sub and then waiting until a Console input.

    Console.WriteLine("Press any key to stop the service")
  4. If not within Visual Studio then it runs the original code to run the service: