Sobes.tech
Middle

How to perform dependency injection in a field using Dagger Hilt?

sobes.tech AI

Answer from AI

Dependency injection in a field using Dagger Hilt is performed by using the @Inject annotation before the field declaration in a class that is itself annotated with @AndroidEntryPoint.

import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

@AndroidEntryPoint // This class will be injected into the application
class MyActivity : AppCompatActivity() {

    @Inject // Injecting dependency
    lateinit var myDependency: MyDependency

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // ...
        myDependency.doSomething()
    }
}

The @Inject annotation indicates to Hilt that this field requires dependency injection. Hilt will find the appropriate provider (for example, a Dagger module) for the type MyDependency and will supply an instance of this type to this field when creating an instance of MyActivity.

It is important to remember that the class MyActivity must be marked with @AndroidEntryPoint so that Hilt can inject dependencies into its fields. Also, the injected field cannot be private (private).