12

In Dagger2's documentation , it say

If your class has @Inject-annotated fields but no @Inject-annotated constructor, Dagger will inject those fields if requested, but will not create new instances. Add a no-argument constructor with the @Inject annotation to indicate that Dagger may create instances as well.

How it inject fields but not create new instances? What's the difference?

Ezio Shiki
  • 745
  • 6
  • 23

1 Answers1

11

"if requested" means "if manually injected", i.e. the object is created by you or some framework (think Android and Activities objects) and then you call 'DaggerMyComponent.inject(myObject);'.

On the other hand, when you provide @Inject annotated constructor Dagger will be able to instantiate objects of this class itself so your class may be in the middle of the dependency graph and object will be automatically be created for you by Dagger.

Usually in Android you inject manually only objects that are created/destroyed for you by android (i.e. you don't control their lifecycle) like Application, Activities, Services, etc.

Also you don't have to worry if you accidentally miss the @Inject annotation on some class' constructor. If your class is the middle of the graph Dagger will catch that there are dependencies that are not satisfied and will fail the compilation with appropriate error.

Ognyan
  • 13,452
  • 5
  • 64
  • 82
  • Thanks!! ..Another question..Could you please have a look at it. I use dagger in a class which in the middle of the dependency graph, this class need some dependencies which already provided by module. First I use field injection , just annotated `@Inject` on field, and no constructor, then it failed ,gave me a null pointer. After that I move field into constructor , annotated `@Inject` on constructor , it worked well . Did I miss something? – Ezio Shiki Nov 11 '15 at 09:39
  • 1
    I am afraid that question is not very clear... Can you post it as separate question with relevant code provided (and put a comment here with link to it)? – Ognyan Nov 11 '15 at 11:10
  • 1
    After read your answer and some blog, I found out what's wrong in my code. I haven't add a empty constructor in dependencies class, before that I thought every dependencies need to define in modules... Have be a little familiar with dagger.. Thank you again! – Ezio Shiki Nov 12 '15 at 05:02