I'm new in dagger , I want to inject context and network (using retrofit) in my classes .
this is my code so far :
@Module
// Safe here as we are dealing with a Dagger 2 module
@Suppress("unused")
object NetworkModule {
@Provides
@Reusable
@JvmStatic
internal fun provideMainApi(retrofit: Retrofit): MainApi {
return retrofit.create(MainApi::class.java)
}
@Provides
@Reusable
@JvmStatic
internal fun provideRetrofitInterface(): Retrofit {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder().addInterceptor(interceptor).build()
return Retrofit.Builder()
.baseUrl(Constants.baseUrl)
.addConverterFactory(MoshiConverterFactory.create())
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.client(client)
.build()
}
}
@Module
class AppModule(private val app: Application) {
@Provides
@Singleton
fun provideApplication() = app
}
this is my component :
@Singleton
@dagger.Component(modules = arrayOf(AppModule::class, NetworkModule::class))
interface AppComponent {
///for injecting retrofit network
fun injectMain(mainRepository: MainRepository)
@dagger.Component.Builder
interface Builder {
fun build(): AppComponent
fun networkModule(networkModule: NetworkModule): Builder
fun appModule(appModule: AppModule):Builder
}
}
I want to use it in my repository , I've a baseRepository :
open class BaseRepository {
private val injector: AppComponent = DaggerAppComponent
.builder()
.networkModule(NetworkModule)
.build()
init {
inject()
}
private fun inject() {
when (this) {
is MainRepository -> injector.injectMain(this)
}
}
}
when I run the app , I get this error "module.AppModule must be set"
I understand the error and I should provie appMOdule in my base repository but the problem is I don't have any application or context in base repository
how should I fix this ?
the second problem I've is this , I've heard that I should once make the dagger and use it in my entire app and I shouldn't make it every time , it means I should use application for that .
but how can I use injector in an application class , it doesn't make sense