【发布时间】:2023-04-06 00:06:01
【问题描述】:
我是 dagger 的新手,我想在我的课程中注入上下文和网络(使用改造)。
这是我目前的代码:
@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
}
这是我的组件:
@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
}
}
我想在我的存储库中使用它,我有一个 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)
}
}
}
当我运行应用程序时,我收到此错误“module.AppModule must be set”
我理解错误,我应该在我的基础存储库中提供 appMOdule,但问题是我在基础存储库中没有任何应用程序或上下文
我应该如何解决这个问题?
我遇到的第二个问题是这个,我听说我应该制作一次匕首并在我的整个应用程序中使用它,我不应该每次都制作它,这意味着我应该为此使用应用程序。
但是如何在应用程序类中使用注入器,这没有意义
【问题讨论】:
标签: android dagger-2 androidinjector