Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 917
haliltprkk Avatar asked Jan 20 '21 16:01

haliltprkk


People also ask

Why field level injection is not recommended?

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.

When would you use a field injection in a Dagger?

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.

What is Hilt dependency injection?

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.

What is the difference between field injection and constructor injection?

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.


1 Answers

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

like image 78
Mücahid Kambur Avatar answered Oct 17 '22 09:10

Mücahid Kambur