Search code examples
androidkotlindependency-injectiondagger-hilt

Field Injection via Hilt outside of Fragment and Activity


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,


Solution

  • 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