Dagger: need help in understanding

Dmitry Gryazin

I have some misunderstandings of the way that dagger works:

  1. There are only two ways to satisfy dependency: whether the @Provide method returns the instance, or the class should have @Singleton annotation, is that right? Must the class constructor have @Inject annotation in the latter case?

  2. As I see, the ObjectGraph generates all the injection stuff. And it's said, that its inject(T instance) should be called to inject fields. However, I can just annotate my field with @Inject and it goes (field's class is @Singletone). ObjectGraph is not needed to satisfy such a dependency, right?

  3. What about injects{} in @Module, what specifically does it give? Plz, provide an example of benefit when you keep all the injectable classes list.

Kirill Boyarshinov
  1. Yes, there are two ways: @Provide methods in modules and @Singleton classes with @Inject at constructor.

Must the class constructor have @Inject annotation in the latter case?

Yes, otherwise object wouldn't be created by Dagger.

  1. I don't think @Singleton with field injection could work. Because @Singleton at class with constructor injection means Dagger is responsible to keep one instance of this class. And it can create this class using constructor injection if all dependencies are satisfied. However, @Singleton with field injection seems misuse to me, cause keeping single instance of this class is user's responsibility now. Dagger can't instantiate this object itself.
    Are you sure this configuration compiles and runs? And if it is check @Inject fields, they should be null by my understanding.

  2. injects={} in @Module returns set of classes passed to ObjectGraph.inject(T class) or ObjectGraph.get(Class<T> class). Referring documentation:

    It is an error to call ObjectGraph.get(java.lang.Class) or ObjectGraph.inject(T) with a type that isn't listed in the injects set for any of the object graph's modules. Making such a call will trigger an IllegalArgumentException at runtime.

This set helps Dagger to perform static analysis to detects errors and unsatisfied dependencies.
You can find some examples in this thread.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related