How can a Windows Service determine its ServiceNam

2019-01-07 19:11发布

I've looked and couldn't find what should be a simple question:

How can a Windows Service determine the ServiceName for which it was started?

I know the installation can hack at the registry and add a command line argument, but logically that seems like it should be unnecessary, hence this question.

I'm hoping to run multiple copies of a single binary more cleanly than the registry hack.

Edit:

This is written in C#. My apps Main() entry point does different things, depending on command line arguments:

  • Install or Uninstall the service. The command line can provide a non-default ServiceName and can change the number of worker threads.
  • Run as a command-line executable (for debugging),
  • Run as a "Windows Service". Here, it creates an instance of my ServiceBase-derived class, then calls System.ServiceProcess.ServiceBase.Run(instance);

Currently, the installation step appends the service name and thread count to the ImagePath in the registry so the app can determine it's ServiceName.

7条回答
一夜七次
2楼-- · 2019-01-07 20:06

What's wrong with this.ServiceName, if you're inside the service.cs?

i.e.:

protected override void OnStart(string[] args)
    {
        Logger.Info($"{this.ServiceName} started on {Environment.MachineName}...");  
    }
查看更多
登录 后发表回答