Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's "Dagger will inject those fields if requested, but will not create new instances" means?

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?

like image 642
Ezio Shiki Avatar asked Nov 08 '15 08:11

Ezio Shiki


1 Answers

"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.

like image 104
Ognyan Avatar answered Sep 26 '22 09:09

Ognyan