Middle
How to pass context in Dagger?
sobes.tech AI
Answer from AI
Through a module that provides Context.
@Module
class AppModule(private val context: Context) {
@Provides
@Singleton
fun provideContext(): Context {
return context
}
// Other provide methods
}
Then this module is used when building the component:
@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {
// Injects
}
And the component is initialized with an instance of AppModule:
class App : Application() {
lateinit var appComponent: AppComponent
override fun onCreate() {
super.onCreate()
appComponent = DaggerAppComponent.builder()
.appModule(AppModule(this)) // Passing the context here
.build()
}
}
Later, the context can be injected into any class that requires it:
class MyService @Inject constructor(private val context: Context) {
// Use the context
}