开发者

Use Settings directly or via a wrapper class?

With reference to the .NET Settings mecha开发者_开发知识库nism, and inspired by a couple of the answers to this question, it seems that some people advocate wrapping the use of Settings via another wrapper class, perhaps a singleton.

Isn't the Settings class a singleton already?

[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

    private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

    public static Settings Default {
        get {
            return defaultInstance;
        }
    }
// rest of class...
}

.

.

.

So, what is the benefit of wrapping Settings in another class and doing this:

int foo = MySettingsWrapper.MyInt;

instead of doing this directly where needed:

int foo = Settings.Default.MyInt;


The Settings class is not a singleton per se. You could do:

var s1 = new Settings();
var s2 = new Settings();
var s3 = new Settings();

However, I believe it won't do you much good, since AFAIK the values of s1, s2 and s3 will all be persisted in the same place:

c:\Documents and Settings>\<username>\[Local Settings\]Application Data\<companyname>\<appdomainname>_<eid>_<hash>\<verison>\user.config

So I suspect:

s1.MyInt = 1;
s1.Save();

will be the same as

s2.MyInt = 1;
s2.save();

For that reason, you get the Settings.Default static property, which returns a single, thread safe instance. I use it all the time as it is, don't see any reason to wrap it. However, you might want to extend it, for example if you wanted to control the location of user.config: How to make designer generated .Net application settings portable


Its a type of dependency injection.

Settings.Default is 1 type of implementation of a settings mechanism.

Adding the wrapper means the implementation code is in one place, not across your code.

It would be easy to swap out that file for another implementation without needing to change your code.

Can be overkill. You need to decide whether you would ever need to swap out that implementation. But think about it, you might find further on down the line some other system that might need to access those settings (SQL Jobs, Remote Services etc).

Typically this "wrapper" should be an implementation of an interface, and you would use a inversion of control container (e.g. Castle.Windsor) to inject the implementation into the runtime environment.


I think the main benefit to wrapping the Settings class with an interface-based class is helps with unit testing: avoids file I/O, settings file location issues, enables Dependency Injection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜