New Android Injector with Dagger 2 — part 2
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 .
Dagger 2.10 released with android support module and android compiler. I think this was a huge change for us and all…medium.com
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.
- Create MainActivity, MainActivityComponent, MainActivityModule
- Map MainActivity to ActivityBuilder(So dagger can understand MainActivity will be injected.)
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.
- Whenever we add our UI component as new subcomponent, we have to map our activity in ActivityBuilder module. This is also repetitive task.
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.
dagger-android-injection - Sample project explains Dependency Injection in Android using dagger-android framework.github.com
part 3 is here.