1. 程式人生 > >Dagger.Android擴充套件庫的使用

Dagger.Android擴充套件庫的使用

One of the central difficulties of writing an Android application using Dagger is that many Android framework classes are instantiated by the OS itself, like Activity and Fragment, but Dagger works best if it can create all the injected objects. Instead, you have to perform members injection in a lifecycle method. This means many classes end up looking like:

public class FrombulationActivity extends Activity {
  @Inject Frombulator frombulator;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // DO THIS FIRST. Otherwise frombulator might be null!
    ((SomeApplicationBaseType) getContext().getApplicationContext())
        .getApplicationComponent()
        .newActivityComponentBuilder()
        .activity(this
) .build() .inject(this); // ... now you can write the exciting code } }

This has a few problems:

  1. Copy-pasting code makes it hard to refactor later on. As more and more developers copy-paste that block, fewer will know what it actually does.
  2. More fundamentally, it requires the type requesting injection (FrombulationActivity) to know about its injector. Even if this is done through interfaces instead of concrete types, it breaks a core principle of dependency injection: a class shouldn’t know anything about how it is injected.

以上是官網原話,巴拉巴拉的說為什麼要使用 Dagger.Android 這個擴充套件庫。按我的理解,大概意思是我們在使用 Dagger2 時,如果往 Activity 、Fragment 等由 Android 系統完成例項化的類中進行註解時,每次都需要建立一個 XXComponent,然後生成一個 DaggerXXComponent,再往 Activity 中註解, DaggerXXComponent..builder().build().inject(),每次都這樣寫,很不方便,於是 Dagger.Android 就誕生了。