简体   繁体   English

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

[英]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? 您是否应该考虑在类中使用Properties.Settings.Default作为依赖项,从而注入它?

eg: 例如:

public class Foo
{
    private _settings;
    private bool _myBool;

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

.
.

or would you consider the use of Settings as an application wide global as good practice? 或者您是否会将Settings作为一种应用程序范围的全球视为良好做法?

eg: 例如:

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与任何支持检索布尔值的基础结构的知识分离。 Foo has no reason to introduce complexity by depending on a settings object, especially if it contains other unrelated values. Foo没有理由通过依赖设置对象来引入复杂性,特别是如果它包含其他不相关的值。

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. 想象一下当您想要在示例#2中通过单元测试更改该组设置时的情况 - 您必须在静态属性getter中使用某种复杂的开关逻辑来容纳它。

Many IoC containers can even provide a singleton implementation when injecting classes like that to assist you. 许多IoC容器甚至可以在注入类似的类时提供单例实现来帮助您。

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. 如果您还使用IoC容器,则务必使用容器注册设置。

I do this for the ConfigurationManager and WebConfigurationManager so that I can inject settings for tests. 我为ConfigurationManagerWebConfigurationManager执行此ConfigurationManager ,以便我可以为测试注入设置。 Nathan Gloyn has wrapped the adapters and interface up already in a project that you can use if you also want to do this. Nathan Gloyn已经将适配器和接口包装在一个项目中 ,如果你也想这样做,你可以使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM