There are times were you want to be able install multiple instances of the same windows service onto the same server (i.e. to support different environments but you have limited servers at your diposal) this poses a problem, you are probably aware windows will not allow more than 1 windows service to be installed with the same service name and when you create a windows service project and an installer you assign the service name at design time.
We need is someway to assign the service name at runtime, well after some extensive googling around I found a way of achieving this, the ProjectInstaller has 2 methods you can override Install and Uninstall which enables us to make changes to the service installer at the at runtime
Yeah that’s great however how do we assign the service name?! Fear not! at our disposal is the Context class that happens to have a Parameters dictionary so we can now capture custom command arguments passed to installutil.exe, enough yapping time for some code:
public override void Install(System.Collections.IDictionary stateSaver)
{
RetrieveServiceName();
base.Install(stateSaver);
}
public override void Uninstall(System.Collections.IDictionary savedState)
{
RetrieveServiceName();
base.Uninstall(savedState);
}
private void RetrieveServiceName()
{
var serviceName = Context.Parameters["servicename"];
if (!string.IsNullOrEmpty(serviceName))
{
this.SomeService.ServiceName = serviceName;
this.SomeService.DisplayName = serviceName;
}
}
In this instance I have made the servicename argument optional in which case it will use the default assigned at design time, you could enforce it in your version.
We can now use this like this:
installutil /servicename=”My Service [SysTest]” d:\pathToMyService\Service.exe
and for uninstall:
installutil /u /servicename=”My Service [SysTest]” d:\pathToMyService\Service.exe
Note for the uninstall you need to supply the servicename so windows how to resolve the service to uninstall
One thing that suprises me is how hidden this implementation is, most results bring up people wanting the same functionality and being told it ain’t possible and articles that suggest messing with config files this to me seems to be a much simpler and nicer way to achieve multiple instances.