I was wondering that is it possible to use field injection outside of fragment or activity? I know I can use constructor injection but, I am wondering is it possible with field injection, as well. I think it was possible with Dagger.
When I try to do something with the injected yclass
field I am getting this error
lateinit property yClass has not been initialized
But it was initialized at the Module I have created.
According to documentation I need to use @AndroidEntryPoint annotation to use field injection, but in that case I am getting this error:
@AndroidEntryPoint base class must extend ComponentActivity, (support) Fragment, View, Service, or BroadcastReceiver.
Note: It is working without an error at the activity
Basically, I want to do something like this,
class XClass() {
@Inject
lateinit var yClass: YClass
}
Thanks in advance,
The reasons why field injection is frowned upon are as follows: You cannot create immutable objects, as you can with constructor injection. Your classes have tight coupling with your DI container and cannot be used outside of it. Your classes cannot be instantiated (for example in unit tests) without reflection.
One of the considerations with Dagger is that injected fields cannot be private. They need to have at least package-private visibility like in the preceding code. Note: Field injection should only be used in Android framework classes where constructor injection cannot be used.
Hilt provides a standard way to incorporate Dagger dependency injection into an Android application. The goals of Hilt are: To simplify Dagger-related infrastructure for Android apps. To create a standard set of components and scopes to ease setup, readability/understanding, and code sharing between apps.
Constructor Injection: State Safe. The object is instantiated to a full state or is not instantiated at all. Field Injection: Consumer uses no-argument constructor. There is no valid way to set state of the object.
To use field injection for custom classes, you need to use @EntryPoint annotation. For more information:
https://developer.android.com/training/dependency-injection/hilt-android#not-supported
or codelab:
https://developer.android.com/codelabs/android-hilt#10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With