New Android Injector with Dagger 2 — part 2

Mert Şimşek
Jun 28, 2017 · 2 min read

I tried to explain dagger-android injection in my previous blogpost. I got some review and people say that it is too complicated and no reason to upgrade to new injection way. I knew it would happen but wanted to explain how it actually works behind the scene. Before you read this part 2 I strongly recommend start with part 1. This part will simplify dagger injection using brand new annotation. @ContributesAndroidInjector .

Lets remember our dagger graph with a visual graphic.

Let’s examine this graph step by step. I will do that for only MainActivity. We can do the rest If we understand the logic.

  • Create an AppComponent and AppModule.

Here we go. We call AndroidInjection.inject(this) in MainActivity and provide whatever instance we want in MainActivityModule.

We just want to inject into MainActivity but we have to do a lot. It can be simplified. How? Let’s check the graph again.

  • UI subcomponents(MainActivityComponent and DetailActivityComponent) are just like bridge in the graph. We don’t even have to use our brain to create this class.

Don’t Repeat Yourself

Authors of dagger realised that problem and brought new solution to this problem. New annotation. @ContributesAndroidInjector . With this annotation, we can easily attach activities/fragments to dagger graph. Before I give you simplified code I wanted to show you simplified dagger graph.

I think it is much more understandable. I simplified my repo with @ContributesAndroidInjector in new branch. You can check my commit.

You can also check my simplified android injection branch from here.

Simplified branch

part 3 is here.

Mert Şimşek

Written by

Sr. Android Developer @lyrebirdstudio