I have a class library used in windows (WPF) and web (ASP.NET) context. The library has settings that are rather user-scoped, if used in windows context and that have to be application-scoped, if used in web context. I would like to declare them as user-scoped and use the default values as “pseudo-application-scoped”. My problem is, that web applications ban user-scoped settings by throwing a configuration error.
What is the best way to handle this, preferably within the frameworks configuration system?
Ok, facing the unavoidable. There are no user-scoped settings in ASP.NET. Class libraries used in mixed client / server environments shouldn’t use them!
Here is the solution I ended with:
For the usage in a server environment (ASP.NET) all settings of class libraries have to be application-scoped.
I introduce a second set of settings for the usage in client environments (WPF). These settings have property names and types identical to the class libraries property names and types, but they can differ in scope and they are located in my main assembly.
With a small piece of code I extend the libraries setting class to inject the user-scoped settings.
namespace ClassLibrary.Properties
{
using System.Configuration;
public sealed partial class Settings {
private ApplicationSettingsBase injectedSettings;
public void InjectSettings(ApplicationSettingsBase settings)
{
injectedSettings = settings;
}
public override object this[string propertyName]
{
get
{
if (injectedSettings != null)
return injectedSettings[propertyName];
return base[propertyName];
}
set
{
base[propertyName] = value;
}
}
}
}
With this extension I can inject the second settings class into the library settings:
ClassLibrary.Properties.Default.InjectSettings(Application.Properties.Settings.Default);
Have a look at the SettingsProvider class by sub classing it you could create a compatible provider for a ASP.NET environment.
It might make changing the current code quite easy because you can keep the current code but have to add a different provider when in ASP.NET.
This gives a nice overview as well