Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SettingsProviderAttribute replacement for application-level custom SettingsProvider

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.

like image 296
Adam Avatar asked Sep 12 '12 23:09

Adam


1 Answers

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;
             }
         }
     }
}
like image 100
drowa Avatar answered Oct 21 '22 06:10

drowa