Skip to content

Dagger2

Weiyi Li edited this page Apr 1, 2018 · 23 revisions

Injecting Activity objects

commit

Injecting Fragment objects commit

  1. its host Activity extends DaggerAppCompatActivity;

  2. it extends DaggerFragment;

  3. Use @Inject to annotate fields of this fragment that REQUIRE dependency, then delete relates code that create the fields instance;

  4. Use @Inject to annotate constructors that PROVIDE dependency, or

  5. Create a @Module annotated class, and within this class use an @Provides annotated method to provide a dependency.

  6. Use ContributesAndroidInjector to install module to dagger graph, because the fragment must be hosted by one activity, that means the activity should also be added to dagger graph:

    This annotation must be applied to an abstract method in a {@link dagger.Module} that returns a concrete Android framework type (e.g. Activity, Fragment, Service, etc). The method should have no parameters.

    /**
     * ArticleListFragment is hosted by ArticleListActivity, so we need to
     * install the fragment's module to this activity.
     */
    @ContributesAndroidInjector(modules = { ArticleListActivityHostedFragment.class })
    abstract ArticleListActivity bindArticleListActivity();
    
    /**
     * The reason to create this class is that this activity maybe host many fragments.
     */
    @Module
    abstract class ArticleListActivityHostedFragment {
    
        @ContributesAndroidInjector(modules = ArticleListFragmentModule.class)
        abstract ArticleListFragment bindArticleListFragment();
    
        // another fragment ...
    }

@Inject doesn’t work everywhere to provide dependency

  • Interfaces can’t be constructed.
  • Third-party classes can’t be annotated.
  • Configurable objects must be configured!

Refer

The following 3 articles introduce how to use Dagger2 in a real Android App Project.

In part1, to attach activities/fragments to dagger graph, it create a lot boilerplate classes and needs a lot repetitive tasks, so is too complicated, so just walk through part1.

In part2, use @ContributesAndroidInjector to simplify dagger graph, check this commit for details

In part3, use DaggerActivity, DaggerFragment, DaggerApplication to reduce boilerplate in your Activity/Fragment/Application, use AndroidInjector<T> in your dagger components to reduce boilerplate too.

New Android Injector with Dagger 2 — part 1, part 2, part 3

Clone this wiki locally