How do I configure the name of a Windows service upon installation (or easily at compile time)?

前端 未结 3 1936
半阙折子戏
半阙折子戏 2020-12-13 07:06

I\'ve created a Windows service in C#, installed it on a server and it is running fine.

Now I want to install the same service again, but running from a different wo

相关标签:
3条回答
  • 2020-12-13 07:34

    Instead of using Environment.GetCommandLineArgs(); the class Installer has a property called Context from which you can access command line arguments passed to InstallUtil structured in a nice StringDictionary.

    0 讨论(0)
  • I tried accessing a configuration using

    ConfigurationManager.OpenExeConfiguration(string exePath)
    

    in the installer, but couldn't get it to work.

    Instead I decided to use System.Environment.GetCommandLineArgs() in the installer like this:

    string[] commandlineArgs = Environment.GetCommandLineArgs();
    
    string servicename;
    string servicedisplayname;
    ParseServiceNameSwitches(
        commandlineArgs, 
        out servicename, 
        out servicedisplayname);
    
    serviceInstaller.ServiceName = servicename;
    serviceInstaller.DisplayName = servicedisplayname;
    

    Now I can install my services using

    InstallUtil.exe /i InstallableService.dll /servicename="myserviceinstance_2" /servicedisplayname="My Service Instance 2"

    I wrote up a more elaborate explanation here.

    0 讨论(0)
  • 2020-12-13 07:50

    You can't pass this in as a command line arg, since InstallUtil doesn't provide the right hooks for that.

    However, you can make your service installer read the ServiceName from a config file. If you look at some code for a typical ServiceInstaller, you'll see it's just a matter of having the appropriate DisplayName and ServiceName properties setup at runtime. These could easily be read from a configuration file instead of being hard-coded.

    0 讨论(0)
提交回复
热议问题