感谢阅读,在将 Java 应用程序转换为 Kotlin 后出现一些注释问题后,我添加了模块组件限定符和范围,并在重建后构建。但我被困在这里,因为我想使用 DaggerFragmentComponent(片段组件)但是它不会导入,因为它在重建后没有创建它。
我只能访问不想执行依赖注入的 DaggerCollections....
片段模块:
package com.example.daggerappkotlin.di.module
import com.example.daggerappkotlin.di.qualifier.FragContext
import com.example.daggerappkotlin.ui.HomeFragment
import dagger.Module
import dagger.Provides
@Module
class FragmentModule(internal var fragment: HomeFragment) {
@FragContext
@Provides
internal fun provideFragment(): HomeFragment {
return fragment
}
@FragContext
@Provides
internal fun provideConnection(): String {
return "Connected Ben Mohammad"
}
}
片段组件:
package com.example.daggerappkotlin.di.component
import android.content.Context
import com.example.daggerappkotlin.di.module.FragmentModule
import com.example.daggerappkotlin.di.qualifier.ApplicationContext
import com.example.daggerappkotlin.di.scope.FragmentScope
import com.example.daggerappkotlin.ui.HomeFragment
import dagger.Component
@FragmentScope
@Component(dependencies = [ApplicationComponent::class], modules = [FragmentModule::class])
interface FragmentComponent {
@ApplicationContext
val context: Context
fun inject(frag: HomeFragment)
}
应用模块:
package com.example.daggerappkotlin.di.module
import android.content.Context
import com.example.daggerappkotlin.MyApplication
import com.example.daggerappkotlin.di.qualifier.ApplicationContext
import com.example.daggerappkotlin.di.qualifier.DatabaseInfo
import com.example.daggerappkotlin.di.qualifier.NetworkInfo
import dagger.Module
import dagger.Provides
@Module
class ApplicationModule(val application: MyApplication) {
@ApplicationContext
@Provides
internal fun provideContext(): Context {
return application
}
@Provides
@DatabaseInfo
internal fun provideDatabaseName(): String {
return "dummy_db"
}
@Provides
@DatabaseInfo
internal fun provideDatabaseVersion(): Int? {
return 1
}
@Provides
@NetworkInfo
internal fun provideApiKey(): String {
return "SOME_API_KEY"
}
}
应用组件:
package com.example.daggerappkotlin.di.component
import android.content.Context
import com.example.daggerappkotlin.MyApplication
import com.example.daggerappkotlin.data.local.DatabaseService
import com.example.daggerappkotlin.data.remote.NetworkService
import com.example.daggerappkotlin.di.module.ApplicationModule
import com.example.daggerappkotlin.di.qualifier.ApplicationContext
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = [ApplicationModule::class])
interface ApplicationComponent {
fun inject(application: MyApplication)
@ApplicationContext
val context: Context
val networkService: NetworkService
val databaseService: DatabaseService
}
我正在尝试在 MainActivity、HomeFragment 和 MyApplication 中进行构建......
