开发者

Use dependency injection for Properties.Settings.Default?

Should you consider the use of Properties.Settings.Default within a class as a dependency, and therefore inject it?

e.g.:

public class Foo
{
    private _settings;
    private bool _myBool;

    public Foo(Settings settings)
   开发者_如何学Python {
        this._settings = settings;
        this._myBool = this._settings.MyBool;
    }
}

.

.

or would you consider the use of Settings as an application wide global as good practice?

e.g.:

public class Foo
{
    private bool _myBool;

    public Foo()
    {
        this._myBool = Properties.Settings.Default.MyBool;
    }
}


I would choose "none of the above" and inject the boolean value directly:

public class Foo
{
    private readonly bool _myBool;

    public Foo(bool myBool)
    {
        _myBool = myBool;
    }
}

This decouples Foo from knowledge of any infrastructure that supports the retrieval of the boolean value. Foo has no reason to introduce complexity by depending on a settings object, especially if it contains other unrelated values.


You may want to encapsulate Settings in a class and have an interface for them. This way, where your settings are coming from can be changed for things like unit testing. If you're also using an IoC container, then by all means register the settings with the container.

I do this for the ConfigurationManager and WebConfigurationManager so that I can inject settings for tests. Nathan Gloyn has wrapped the adapters and interface up already in a project that you can use if you also want to do this.


They should be passed in as a dependency. Imagine the scenario when you want to change that set of settings via Unit Test in your example #2 - you would have to have some kind of complicated switch logic in the static property getter to accomdate that.

Many IoC containers can even provide a singleton implementation when injecting classes like that to assist you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜