Hilt & Dagger Annotations: V1.0 - @androiddev
Hilt & Dagger Annotations: V1.0 - @androiddev
v1.0 - @AndroidDev
@Inject @AndroidEntryPoint
Field injection. Populates fields in
class MyActivity : AppCompatActivity() {
@AndroidEntryPoint annotated classes.
@Inject lateinit var adapter: AnalyticsAdapter
Fields cannot be private. ...
}
@InstallIn(ApplicationComponent::class)
Class in which you can add bindings for
@Module types that cannot be constructor injected.
@Module
class AnalyticsModule { ... }
@InstallIn(ApplicationComponent::class)
@Module
class AnalyticsModule {
@InstallIn(ApplicationComponent::class)
Shorthand for binding an interface type: @Module
abstract class AnalyticsModule {
- Methods must be in a module.
@Binds - @Binds annotated methods must be @Binds
abstract. abstract fun bindsAnalyticsService(
- Return type is the binding type.
analyticsServiceImpl: AnalyticsServiceImpl
- Parameter is the implementation type.
): AnalyticsService
}
@InstallIn(ApplicationComponent::class)
Obtain dependencies in classes that are @EntryPoint
either not supported directly by Hilt or interface MyContentProviderEntryPoint {
cannot use Hilt. fun analyticsService(): AnalyticsService
}
The interface annotated with @EntryPoint
must also be annotated with @InstallIn override fun query(...): Cursor {
passing in the Hilt predefined component val appContext =
@Entry Point from which that dependency is taken context?.applicationContext
from. ?: throw IllegalStateException()
val entryPoint =
Access the bindings using the appropriate
EntryPointAccessors.fromApplication(
static method from EntryPointAccessors
appContext,
passing in an instance of the class with
the DI container (which matches the value MyContentProviderEntryPoint::class.java)
in the @InstallIn annotation) and the entry val analyticsService =
point interface class. entryPoint.analyticsService()
...
}
}
* The code example for this annotation assumes you’re using the Gradle plugin ** This annotation is avaiable using the androidx.hilt.hilt-lifecycle-viewmodel library