DEV Community

Gaurav Chaddha
Gaurav Chaddha

Posted on

Practical guide to Dagger 2

The post was published at my blog. If you don't have any idea about dependency injection or dagger, head over to the article link above.

Keep reading if you have an idea about dagger annotations like @Inject, @Module, @Provides and @Component. These rules are for simple use-cases of dependency injection.

Rule-set:

  1. Use @Inject on constructors wherever you can (To declare dependencies).

  2. Make modules for stuff you can’t instantiate directly (e.g. Retrofit client as it’s built by it’s builder) or for stuff you can’t create like Context.

  3. Also make ‘provides’ method in modules if you want to inject interfaces instead of implementations.

  4. Use @Singleton if you want the dependencies to remain a Singleton.

  5. Include all the required modules in the component and define where that component will inject dependencies to.

  6. Use @Inject to ask dagger to inject dependencies you have declared.

Latest comments (0)