Professional Documents
Culture Documents
Hilt & Dagger Annotations: V2.33 - @androiddev
Hilt & Dagger Annotations: V2.33 - @androiddev
v2.33 - @AndroidDev
@Inject @AndroidEntryPoint
Field injection. Populates fields in
class MyActivity : AppCompatActivity() {
@AndroidEntryPoint annotated classes.
@Inject lateinit var adapter: AnalyticsAdapter
Fields cannot be private. ...
}
@HiltViewModel
class MyViewModel @Inject constructor(
Tells Hilt how to provide instances of an
@HiltViewModel private val adapter: AnalyticsAdapter,
Architecture Component ViewModel.
private val state: SavedStateHandle
): ViewModel() { ... }
@InstallIn(SingletonComponent::class)
Class in which you can add bindings for
@Module types that cannot be constructor injected.
@Module
class AnalyticsModule { ... }
@InstallIn(SingletonComponent::class)
@Module
class AnalyticsModule {
@InstallIn(SingletonComponent::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(SingletonComponent::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()
...
}
}