DEV Community

Gaurav Chaddha
Gaurav Chaddha

Posted on

4

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more