Reputation: 1508
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,
Upvotes: 20
Views: 14438
Reputation: 64
For anyone that is looking for an alternative answer I've made an library to inject custom classes anywhere. Even in functions! The library is at https://github.com/dewantawsif/flexible-hilt. After some tweaking to the custom classes it's as simple as
fun printPetType(pet: Pet = getFromFlexibleHilt()) {
println(pet.type)
}
Upvotes: 0
Reputation: 1678
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
Upvotes: 17