Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows service - how to make name configurable

I have written a windows service in C#. The requirement at the beginning was that I should be running only one instance of that service, but that has changed and now I need multiple instances. This is why I need to change the service name according to the configuration file.

What would be the best way to make it register with the correct name ? Should I write another tool to do it? Can I just read the name from App.config file and set it in the service and installer classes accordingly ?

PS> I do not really understand how that thing with names work - one should set names in service and installer classes, but then when installing with installutil.exe or even powershell new-service the name also should be specified. Does that have to be the same? Or one overrides another?

like image 609
kubal5003 Avatar asked May 18 '11 11:05

kubal5003


2 Answers

You can simply read it from the app.config and set it in the installer classes.
Normally, a class that inherits from Installer is automatically created. It contains a member of type System.ServiceProcess.ServiceInstaller, most likely named serviceProcessInstaller1. This has a property ServiceName you can set. Additionally, you need to set the ServiceName property of the ServiceBase derived class to the same value.
In a default implementation, these are set to constant values in the respective InitializeComponent methods, but there is no reason to stick with this. It can be done dynamically without problems.

like image 125
Daniel Hilgarth Avatar answered Nov 09 '22 09:11

Daniel Hilgarth


I though I'd add my 2 cents since I ran into this. I have a file called "ProjectInstaller.cs" with designer and resources under it. Opening it up in design shows MyServiceInstaller and MyProjectInstaller as items on the design surface. I was able to change the names in the ProjectInstaller() constructor, and manually loaded the config file from the module directory:

public ProjectInstaller()
{
    InitializeComponent();

    var config = ConfigurationManager.OpenExeConfiguration(this.GetType().Assembly.Location);

    if (config.AppSettings.Settings["ServiceName"] != null)
    {
        this.MyServiceInstaller.ServiceName = config.AppSettings.Settings["ServiceName"].Value;
    }
    if (config.AppSettings.Settings["DisplayName"] != null)
    {
        this.MyServiceInstaller.DisplayName = config.AppSettings.Settings["DisplayName"].Value;
    }
}
like image 34
Jason Goemaat Avatar answered Nov 09 '22 08:11

Jason Goemaat