Question

I need to store 2 sections of settings in app.config and based on the value passed when initialising the class I will load one of the sections of settings.

This is what I need to achieve ideally:

Class

Public Class SiteSettings

    Sub New(ByVal Id As Integer)
            If Id = 1 Then
                'Load in group1 settings.
                'Ideally the settings will be available as properties
            Else
                'Load in group2 settings
            End If
    End Sub
    ...
End Class

Code

Dim objSettings = New SiteSettings(Id)

'just to demo what I'm trying to achieve
response.Write(objSettings.setting1)

App.config

<siteSettings>
    <section name="group1">
        <setting1 value="abc" />
    </section>
    <section name="group2">
        <setting1 value="xyz" />
    </section>
</siteSettings>
Was it helpful?

Solution

It shouldn't be hard to read in your own settings. There is a lot of code out there for reading custom config settings - just look at the links under "Related" on this page. If your settings object is serializable, you can retrieve an instance from app.config, using custom settings support.

If you want to instantiate an object and encapsulate all the settings-reading logic in the constructor, you'll probably have to write a wrapper for your actual custom config setting, sort of like this:

public interface ISettings
{
     int Setting1 { get; set; }
}

[Serializable]
public class ActualSettings : ISettings
{
    public int Setting1 { get;set;}
}

public class SettingsAdapter : ISettings
{
    private ISettings settings;
    public SettingsAdapter(int id)
    {
        if(id == 1)
            settings = // code to retrieve instance #1 from app.config
        else
            settings = // code to retrieve instance #2 from app.config
    }

    public int Setting1 { 
       get { return settings.Setting1; }
       set { settings.Setting1 = value; }
    }
}

OTHER TIPS

This may be beyond what is supported in the app.config file. However, you could certainly include your own xml file in the application directory and parse it with XPath to load your settings as you describe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top