Search code examples
vb.netwindows-servicesapplication-settings

Default values are being used for My.Settings instead of those in the app.config (for a Windows service)


A Windows service written in VB.NET is using the My.Settings namespace for simplicity. There are only three settings to read, and these are read within the constructor of the ServiceLauncher.

I am attempting to install the service as such:

installutil GID.ServiceLauncher.exe

And this is successful, however the config settings it is using are not the ones within the GID.ServiceLauncher.exe.config file, instead it is using the ones baked into the app as Default Settings within Settings.Designer.vb (marked with DefaultSettingValueAttribute). [The questionable wisdom of Microsoft not allowing a developer to ignore default settings is another question entirely].

How can I further diagnose this issue, and maybe force a reload of settings? I tried calling My.Settings.Default.Reload, however this did nothing. All settings are application settings, and only differ by "value" from those in the auto generated file.

I have successfully attached the debugger using System.Diagnostics.Debugger.Launch() and true enough, the settings are still the default settings.

In anticipation of the question, the background: The reason for requiring configuration settings is because this is a very straightforward service that simply executes an exe; and this exe is in configurable location. There are other reasons also, such as I wish to have the service name configurable without recompiling.


Solution

  • I discovered that because the installer runs in the same process as InstallUtil.exe the config file is never found for a Windows Service. Similar article here on msdn

    Therefore I rolled my own simple solution inspired by this. See below for new code:

    Friend Function GetConfigurationValue(ByVal key As String) As String
        Dim service = System.Reflection.Assembly.GetAssembly(GetType(ProjectInstaller))
        Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(service.Location)
        Dim keyValue As String = config.AppSettings.Settings(key).Value
    
        If String.IsNullOrEmpty(keyValue) Then
            Throw New IndexOutOfRangeException(String.Format("Settings collection does not contain the requested key:[{0}]", key))
        End If
    
        Return keyValue
    End Function
    

    Alternative solutions:

    Passing parameters in to InstallUtil
    Daenibuq (another abstraction on wrapping System.ServiceProcess)