Where (layer) should DI be used?

Is there any layer where it is bad to use DI practice? In the previous question, the user mentioned that DI should only be used in the user interface layer.

+3
source share
4 answers

I think that you can misinterpret the answer of Daren Dimitrov . If I'm not mistaken, the line that raised this question is this: "You also should not create a dependency with a DI framework in the business layers of the application."

I believe that he says that all information / dependency comparisons should be created at the highest level of the application. This does not mean that dependencies will not be present at all levels of your application, since the lower levels are not responsible for setting up mappings.

If my interpretation is correct, I agree with him - configure dependency mappings on the surface of your application. If instead he says that you should never allow dependency in the lower layers, then I will have to disagree.

+5
source

(DI) . , DI - , . DI , . , DI, DI Service .

, , , ? , : - (-). , . .

DI DI. DI, .

, DI, :

public class Foo : IFoo
{
    private readonly IBar bar;

    public Foo(IBar bar)
    {
        if (bar == null)
        {
            throw new ArgumentNullException("bar");
        }

        this.bar = bar;
    }

    public IBaz Baz(ISnafu snafu)
    {
        return this.bar.Snafize(snafu).ToBaz();
    }
}

IBaz , Foo. , , , Foo IBar - IFoo:

public class MyClass : ISomeInterface
{
    private readonly IFoo foo;

    public MyClass(IFoo foo)
    {
        if (foo == null)
        {
            throw new ArgumentNullException("foo");
        }

        this.foo = foo;
    }

    // ...
}

, DI. .

+4

DI , , → , → - . , , , DI , , .

+3

I do not agree with this statement. Either the previous question you are quoting is incorrect, or you misinterpreted it.

DI, of course, not only in the user interface layer. I would agree with this only if the controllers are part of the presentation layer.

You use DI wherever appropriate dependencies can be provided.

If you decide to use a factory or a DI solution of your choice.

+2
source

Source: https://habr.com/ru/post/1747901/