Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

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

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 working directory, having a different config file etc. Thus, I would like to have two (or more) instances of the same service running simultaneously. Initially, this isn't possible since the installer will complain that there's already a service with the given name installed.

I can overcome this by changing my code, setting the ServiceBase.ServiceName property to a new value, then recompiling and running InstallUtil.exe again. However, I would much prefer if I could set the service name at install-time, i.e. ideally I would do something like

InstallUtil.exe /i /servicename="MyService Instance 2" MyService.exe

If this isn't achievable (I very much doubt it), I would like to be able to inject the service name when I build the service. I thought it might be possible to use some sort of build event, use a clever msbuild or nant trick or something along those lines, but I haven't got a clue.

Any suggestions would be greatly appreciated.

Thank you for your time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...