我是匕首的新手,我想在我的课程中注入上下文和网络(使用改造)。
这是我到目前为止的代码:
@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”
我理解该错误,我应该在基本存储库中提供appMOdule,但问题是我在基本存储库中没有任何应用程序或上下文
我该如何解决?
我遇到的第二个问题是,我听说我应该做一次匕首并在我的整个应用程序中使用它,我不应该每次都使用它,这意味着我应该为此使用应用程序。
但是我如何在应用程序类中使用注入器,这没有意义
这里解释了这个项目的目的:
https://medium.com/androiddevelopers/google-i-o-2018-app-architecture-and-testing-f546e37fc7eb
您也可以通过此项目检查Dagger分支:
https://github.com/android/architecture-samples
全部由Jose Alcerreca和其他一些人完成。这些是Google关于Android的指南,大多数问题都会得到解答。
但是我如何在应用程序类中使用注入器,这没有意义有一个DaggerApplication类,您可以根据需要扩展和注入您的App类。
我正在告诉您所有这些信息,因为我认为您已经从旧资料中学到了Dagger。我会在您的代码中更改很多内容。
另外,我从1.5年开始使用Dagger,而且我从未像这样的代码编写过代码:BaseRepository。我只使用@Inject注释,这就是所有与Dagger不相关的类。在存储库中创建组件? ->永不!这是您的班级应该到处结束的方式。
class Repostory @Inject constructor(
private val dependency1: Dependency1
) {}
class Activity {
@Inject lateinit var dependency2: Dependency2
}