0

Even though there are similar questions, I couldn't find any that solves mine. I have a simple program that runs as a service and I want to start it programatically. It's as simple as this:

private static void StartService()
{
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[]
    {
        new MyService()
    };

    ServiceBase.Run(ServicesToRun);
}

As expected, I can't just start my service without installing it. Windows gives me the following error message:

Cannot start service from command line or debugger. A windows service must first be installed using installutil.exe and then started with service explorer, Windows services administrative tool or NET start.

So far so good. So I went there and did just as the docs says:

installutil <my_project>.exe

The installation was successful and I can even start my service from Service Manager or net start. The only problem is: when I debug my application (via F5), Windows keeps showing me the exact same message: Cannot start service (...).

I've found a solution here that uses this:

public void onDebug()
{
    OnStart(null);
}

Which allows me to run and debug my application normally, but I actually need it to run as a service and Windows refuses to start that way. Is there anything I'm missing?

Airn5475
  • 2,452
  • 29
  • 51
Pedro Corso
  • 557
  • 8
  • 22
  • 1
    I'd take a look at http://topshelf-project.com/. It makes developing windows services significantly easier. – Dirk Aug 02 '19 at 19:10

1 Answers1

0

It is not in your power to just start a Service like a normal programm. The Service must be registered with and started by the Service manager. That is one of the (many) rules of Windows services. And you have to repeat that for every new build.

As this and other Service related rules (no interactive sessions) can make developing them a Pain, a common approach is to develop them using a console application. I could not find my ideal example, but I found something like it: https://alastaircrabtree.com/how-to-run-a-dotnet-windows-service-as-a-console-app/

Of course a better longterm plan might be to stop using Services alltogether and switch over to the Windows Task Scheduler. It depends heavily on what exactly you need this code to be able to do in practice.

Christopher
  • 9,634
  • 2
  • 17
  • 31