Dagger2 Experience

Suppose we have 2 classes : A, B .

class A : — The class which can be dependency and we can use into other classes by using @Inject A variableA; (In Simple words,It is class which want to be injected into other classes )

class B: — The class who wants to inject the depencies. class B wants to inject other dependencies into itself. ( If you use Interface i.e. @Inject MyInterface then this will not work for sure!)

So now on the basis of this metaphor,

Class A can become injectable in only 2 ways:-

  1. By Providing its object using the method with @Provides or @Produces annotation.
  2. By Providing the Injectable Constructor, So Dagger can automatically create the class A object implicity!

And finally We must provide the method in Component interface so Dagger can inject the dependcies in the component :)

@Scope : We use scope annotation to better architecuring app.

The rules with scope is:-

  1. We have to add the @scope annotation to component interface & also where we providing the object that wants to have scope.

The other things notable i found during dagger2 implementation is:-

  1. We can use @Inject annotation for interface but if the implementor class of that interface also has injection dependencies then We cant provide object of interface. in short if the class we want to inject has also injectable dependency then that file should be declared in dagger2 with @provides or @produces.

Update — -> Dagger 2.6 05/09/2014


To use Dagger2 we have to remember 2 facts about Field injection when we use @inject AnObject iamObject;

It should inject itself by using @component interface where we define inject method OR it should make the consturctor injectable by defining @inject annotation on top of constructor so Dagger2 can call it.!

Very Important : —

@Provides @Singleton File provideStorageDirectory(TimestampApplication app) {
File storageDir =
new File(Environment.getExternalStorageDirectory(), app.getString(R.string.app_name));
return storageDir;

if we define provide method like this that is we are expecting Application object to be injected then we have to define the accessor method in @Component interface.

TimestampApplication app();
so Dagger 2 know that it has to get TimestampApplication object using the provided method (i.e. method with @provide annotation). So Dagger2 automatically then inject the parameter :)

If you found this article helpful, please do hit the heart button below and let me know on Twitter. Thanks!

Let’s get connect on facebook, twitter, github and linkedin.