对Properties.Settings.Default使用依赖注入?

And*_*ndy 5 c# settings dependency-injection winforms

您是否应该考虑Properties.Settings.Default在类中使用作为依赖项,并因此注入它?

例如:

public class Foo
{
    private _settings;
    private bool _myBool;

    public Foo(Settings settings)
    {
        this._settings = settings;
        this._myBool = this._settings.MyBool;
    }
}
Run Code Online (Sandbox Code Playgroud)

.
.

或者您是否会考虑将Settings全球应用作为良好做法?

例如:

public class Foo
{
    private bool _myBool;

    public Foo()
    {
        this._myBool = Properties.Settings.Default.MyBool;
    }
}
Run Code Online (Sandbox Code Playgroud)

Rus*_*Cam 2

您可能希望将设置封装在一个类中并为它们提供一个接口。这样,您的设置就可以更改以进行单元测试等操作。如果您还使用 IoC 容器,那么请务必向容器注册设置。

我这样做是为了ConfigurationManager和 ,WebConfigurationManager以便我可以注入测试设置。Nathan Gloyn 已将适配器和接口封装在一个项目中,如果您也想这样做,您可以使用该项目。