c# - 对 Properties.Settings.Default 使用依赖注入(inject)?

标签 c# winforms dependency-injection settings

您是否应该将类中 Properties.Settings.Default 的使用视为依赖项并因此注入(inject)它?

例如:

public class Foo
{
    private _settings;
    private bool _myBool;

    public Foo(Settings settings)
    {
        this._settings = settings;
        this._myBool = this._settings.MyBool;
    }
}

.
.

或者您是否认为使用Settings 作为全局应用程序的良好做法?

例如:

public class Foo
{
    private bool _myBool;

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

最佳答案

我会选择“以上都不是”并直接注入(inject) bool 值:

public class Foo
{
    private readonly bool _myBool;

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

这将 Foo 与支持 bool 值检索的任何基础设施的知识分离。 Foo 没有理由通过依赖设置对象来引入复杂性,尤其是当它包含其他不相关的值时。

关于c# - 对 Properties.Settings.Default 使用依赖注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7125443/

相关文章:

C# - 终止 Application.Run()

c# - 如何从统一容器中按名称获取类型的所有实例?

java - 使用 Spring 注入(inject)基于泛型类型的类对象

c# - spring - 通过对象属性表示的未满足的依赖关系

c# - 不同 DbContext 的并行执行比非并行版本慢

c# - 从 C# 中的 msi 文件中获取产品名称

java - 将安全 token 功能从 C# 重新创建为 Java

c# - 如果大于 C#

.net - 在 windows.forms 之间传递信息的最佳实践

c# - 在 WinForms 应用程序中编译 ASPX