Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    {
        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;
    }
}
like image 328
Andy Avatar asked Aug 19 '11 17:08

Andy


People also ask

When should dependency injection be used?

More specifically, dependency injection is effective in these situations: You need to inject configuration data into one or more components. You need to inject the same dependency into multiple components. You need to inject different implementations of the same dependency.

How do you inject a property?

Property injection is a type of dependency injection where dependencies are provided through properties. Visit the Dependency Injection chapter to learn more about it. Let's understand how we can perform property injection using Unity container. Consider the following example classes.

What is the purpose of dependency injection?

Dependency Injection (DI) is a design pattern used to implement IoC. It allows the creation of dependent objects outside of a class and provides those objects to a class through different ways. Using DI, we move the creation and binding of the dependent objects outside of the class that depends on them.

What is dependency injection with example?

Dependency injection (DI) is a technique widely used in programming and well suited to Android development. By following the principles of DI, you lay the groundwork for good app architecture. Implementing dependency injection provides you with the following advantages: Reusability of code.


1 Answers

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.

like image 114
Bryan Watts Avatar answered Sep 22 '22 13:09

Bryan Watts