Search code examples
androiddependency-injectiondagger-2

What does "You should only declare modules once in a component" mean in Dagger 2?


This is probably very straight forward, but I'm confused by the line "You should only declare modules once in a component" in the Android Dagger 2 best practices documentation. What is this line saying I shouldn't do?


Solution

  • The advice is about structuring how your modules include other modules, encouraging you to be careful with it to preserve your ability to make changes in the future. Including the same module twice through two separate paths is allowed, but is poor practice and can have consequences later.

    This is expanded further in the Working with Modules heading further down in the page.

    Once a module has been added to either a component or another module, it's already in the Dagger graph; Dagger can provide those objects in that component. Before adding a module, check if that module is part of the Dagger graph already by checking if it's already added to the component or by compiling the project and seeing if Dagger can find the required dependencies for that module.

    Good practice dictates that modules should only be declared once in a component (outside of specific advanced Dagger use cases).

    The documentation goes on to describe how Dagger will de-duplicate modules that are accessible in the same component through two paths, which can happen if you use the includes field on the @Module annotation. That de-duplication prevents Dagger from complaining if you include a module twice, but it may make it more difficult to refactor in the future. This is especially true if two different modules expose the same binding (e.g. @Binds and @Provides methods with the same qualifier annotations and return values) but with different implementations: Dagger will not allow those conflicting bindings to exist in the same component, so refactoring becomes easier if you can reason well about exactly which modules are in your Component and how they are included.