Dagger 2 Tutorial For Android: Advanced | raywenderlich.com

Dagger is arguably the most used Dependency Injection, or DI, framework for Android. Many Android projects use Dagger to simplify building and providing dependencies across the app. It gives you the ability to create specific scopes, modules, and components, where each forms a piece of a puzzle: The dependency graph. Unfortunately, Dagger can’t solve every […]

This is a companion discussion topic for the original entry at https://www.raywenderlich.com/6583167-dagger-2-tutorial-for-android-advanced

It is not really a good idea to make your fragment dependencies singleton and make them live for the entire lifetime of the app. Imagine you have a big application with a lot of dependencies flying around. You would have memory problems. I would rather be creating a fragment component with a custom scope to inject fragments. AppComponent should only provide real singletons such as network client, database, etc.

Also, why would you provide a repository via component here? .appModule(AppModule(MemoryNewsRepository()))
The example above can be very misleading.

You can simply use constructor injection and provide it to the dependency tree, you don’t even need a module for the classes that you own. Using modules with dependencies is not a good Dagger 2 practice. Keep the modules dumb and if you are using provide methods make them static(In Kotlin you do not even need @JvmStatic anymore just use the Kotlin object) or use abstract modules with @Binds anytime possible.By doing this you ll make Dagger implement less classes and improve the performance. If you need to add something to the dependency tree during runtime (such as applicationContext) @BindsInstance is enough.

I suggest you re-consider your article to avoid misunderstandings.

Hi @tartarjr
Thank you very much for your messages. The goal of the tutorial is not to describe a single solution to copy and paste but to understand what’s behind Dagger in order to consider the pros and cons of all the possible options. In your messages, you also provided 4 different solutions, all valid, for the problem described in the tutorial.
What you said about the Fragment is right but it’s part of the process which allow me to describe the problem and the possible solution which will be part of the second part of tutorial, we’re going to publish very soon.


Hi Max! Thank you for your reply. I see, looking forward to read the second part.

This tutorial is more than six months old so questions are no longer supported at the moment for it. Thank you!