Isn't Dagger 2 for Android a DI framework but glorified Service Locator?

For example, let's say that my vacation adapter created with Retrofit lives inside the Application class. I would like to get it inside an Activity, so I will write the following code:

public class MainActivity extends Activity {
    @Inject MyRestAdapter mRestAdapter;

    @Override 
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((GlobalApplication) getApplication()).getComponent().inject(this);
    }
}

Of course, he will do his job. But ... How does this differ from calling the getApplication () method, and then explicitly pulls MyRestAdapter into MainActivity? Yes, Dagger 2 will simplify the setup by automatically bringing everything to Activity, but you still need to explicitly indicate where you need these dependencies from, and that, if I understand correctly, the whole DI goal wins. Can I say that Dagger 2 is a β€œsemi-automatic service locator”, or is it just the tutorials that misled me, and is there a proper way to embed dependencies with Dagger 2 in a view or activity from an application?

+4
source share
2 answers

"DI DI", , , . , , Activity Android, , , , , , , . , Activity ( TextView [0]), DI , .

" " . , , -DI . ( ).

, , , , , - . , , . MainActivity AnalyticsLogger - ? , , , .

[0], Paint

0

, . , , , Android. AndroidInjection.inject(this) onCreate. " ". , Dagger / , , , , (, ) . , Android - / .

0

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


All Articles