Field Injection via Hilt outside of Fragment and Activity
Asked Answered
S

2

20

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,

Simplistic answered 20/1, 2021 at 16:29 Comment(4)
@Halitprkk Can you please help me in the same problem , Actually I want to access the Hilt in my helper class but did not get any success, please help me on it Thanks – Aegaeon
Hi @RavindraKushwaha, Mücahid Kambur's answer should do the job actually. Also for that problem, I had not use the injection for my helper classes. That is why i am not able to help πŸ€·β€β™‚οΈ – Simplistic
Thanks for the input..I have done for the helper class to☺️ – Aegaeon
That is awesome πŸ™‚ – Simplistic
V
17

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

Viradis answered 20/1, 2021 at 21:30 Comment(4)
As I understand, I still need appContext to be able to get dependency when defining an entry point, is there a way to do without it? – Suttle
Can I use Field injection in a non activity, non fragment CLASS not interface? – Becoming
The example in the docs is a bit confusing. It makes it look like it's a lot of work. In fact you only need one such an entry point interface providing access to all you injectable classes which you can use from anywhere you want. – Fons
And what if you have an interface that's already being injected happily into non custom clases and you just need it in one custom class? – Gillard
N
0

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)
}
Nordine answered 6/5, 2024 at 15:6 Comment(0)

© 2022 - 2025 β€” McMap. All rights reserved.