17

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,

haliltprkk
  • 1,428
  • 3
  • 14
  • 26

1 Answers1

14

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

Mücahid Kambur
  • 1,610
  • 13
  • 10
  • 2
    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? – Anurag Shukla May 06 '21 at 14:43
  • 1
    Can I use Field injection in a non activity, non fragment CLASS not interface? – Ahmad Shahwaiz Sep 13 '21 at 14:22
  • 1
    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. – Slion Jan 06 '22 at 17:01