Middle
Kuidas teha sõltuvuste sisestust väljal, kasutades Dagger Hilt?
sobes.tech AI
Vastus AI-lt
Dependence injection into a field using Dagger Hilt is performed by using the @Inject annotation before the field declaration in a class 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 a dependency. Hilt will find a suitable provider (e.g., a Dagger module) for the MyDependency type and provide 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 annotated with @AndroidEntryPoint so that Hilt can inject dependencies into its fields. Also, the injected field cannot be private (private).