What "Dagger will enter these fields, if requested, but will not create new instances" means?

Dagger2 documentation says

If your class has @ Inject-annotated fields, but no @ Inject-annotated constructor, the Dagger will enter these fields if necessary, but will not create new instances. Add a constructor with no argument with @ Insert annotation to indicate that the Dagger can instantiate as well.

How does he enter fields but not create new instances? What's the difference?

+7
android dependency-injection dagger-2
source share
1 answer

โ€œif requestedโ€ means โ€œif manually enteredโ€, i.e. an object is created by you or some structure (I think Android and Activities objects), and then you call 'DaggerMyComponent.inject (myObject);'.

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

Typically, in Android, you manually enter only those objects that were created / destroyed for you using android (i.e. you do not control their life cycle), for example, Application, Activities, Services, etc.

Also, you donโ€™t need to worry if you accidentally missed the @Inject annotation in the constructor of any class. If your class is the middle of the graph, the Dagger will catch that there are dependencies that are not satisfied and will not compile the compilation with the corresponding error.

+7
source share

All Articles