SettingsProviderAttribute replacement for application-level custom SettingsProvider
Asked Answered
G

1

9

In a .NET application, if you have specific Settings need, such as storing them in DB, then you could replace LocalFileSettingsProvider with a custom settings provider of your, examples:

Create a Custom Settings Provider to Share Settings Between Applications

Creating a Custom Settings Provider

To declare the settings class (the one that inherits ApplicationSettingsBase) that you want to use a specific provider, you decorate it with SettingsProviderAttribute and pass your provider type as a parameter [SettingsProvider(typeof(MyCustomProvider))], otherwise it will use the default LocalFileSettingsProvider.

My question: Is there a configuration or a trick I could use to force my application to use my custom provider through-out the application without using an attribute?

The reason is that I am loading plugins via MEF and the plugins might be written via 3rd party and I don't want them to be concerned with how settings are being dealt with.

Googolplex answered 12/9, 2012 at 23:18 Comment(0)
S
8

You could try the following code. It basically changes the default provider to an arbitrary one during the construction of the Settings object. Note that I never tested this code.

internal sealed partial class Settings {

    public Settings() {

        SettingsProvider provider = CreateAnArbitraryProviderHere();

        // Try to re-use an existing provider, since we cannot have multiple providers
        // with same name.
        if (Providers[provider.Name] == null)
            Providers.Add(provider);
         else
            provider = Providers[provider.Name];

        // Change default provider.
        foreach (SettingsProperty property in Properties)
        {
            if (
                property.PropertyType.GetCustomAttributes(
                    typeof(SettingsProviderAttribute),
                    false
                ).Length == 0
             )
             {
                 property.Provider = provider;
             }
         }
     }
}
Subservient answered 10/12, 2012 at 18:58 Comment(2)
this works, but one line needs to be updated --> provider = Providers[provider .Name] as ArbitrarySettingsProvider ;Swordtail
SettingsProvider does not appear to have a 'Name' property...? Ahh, I was missing a reference to System.Configuration in my assemblyConsonance

© 2022 - 2024 — McMap. All rights reserved.