Category Archives: Windows Service

Pardon, what’s your name? Dynamically naming a windows service using app.config

K, here it is. I needed to run multiple instance of a windows service with different names.

Here is how I dynamically named my C# windows service with an entry in the app.config.

I have a standard .net ProjectInstaller class

[RunInstaller(true)]
public class ProjectInstaller : System.Configuration.Install.Installer
{
private readonly Configuration _config;
private readonly string _serviceName;
private readonly string _serviceDescription;

In the constructor, I use reflection to find the app.config for MY service. Installutil.exe will not see your app config as it is not running out of your bin. To find yours, use the GetAssbembly call below.

public ProjectInstaller()
{
Assembly service = Assembly.GetAssembly(typeof(SpecimenStatusingRealtimeService));
_config = ConfigurationManager.OpenExeConfiguration(service.Location);
_serviceName = (_config.AppSettings.Settings[“ServiceName”]).Value;
_serviceDescription = (_config.AppSettings.Settings[“ServiceDescription”]).Value;

InitializeComponent();

}

In the InitializeComponent call, give the name you pulled from your app.config.

        private void InitializeComponent()
{
this._serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this._serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
this._serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this._serviceProcessInstaller1.Password = null;
this._serviceProcessInstaller1.Username = null;

this._serviceInstaller1.Description = _serviceDescription;
this._serviceInstaller1.ServiceName = _serviceName;

this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this._serviceProcessInstaller1,
this._serviceInstaller1});

}

Neat Huh?

When you run InstallUtil.exe, it will pull the service name and description from your app.config and you are on your way.

If you do this, do not ever move the installer icon on the designer surface in Visual Studio. If you do, you will have to re-add your name lines in the InitializeComponent method.

Happy Coding,

Jim