我正面临这个问题,在多模块android项目与刀柄。
kotlin.UninitializedPropertyAccessException: lateinit property repository has not been initialized in MyViewModel
我的模块是
Module
‘应用模块’
@AndroidEntryPoint
class MainFragment : Fragment() {
private lateinit var viewModel: MainViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.main_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
viewModel.test()
}}
'ViewModel模块‘
class MainViewModel @ViewModelInject constructor(private val repository: MyUsecase): ViewModel() {
fun test(){
repository.test()
}}
'UseCase模块‘
class MyUsecase @Inject constructor() {
@Inject
lateinit var feature: Feature
fun doThing() {
feature.doThing()
}
@Module
@InstallIn(ApplicationComponent::class)
object FeatureModule {
@Provides
fun feature(realFeature: RealFeature): Feature = realFeature
}
}
'DataSource模块‘
interface Feature {
fun doThing()
}
class RealFeature : Feature {
override fun doThing() {
Log.v("Feature", "Doing the thing!")
}
}
依赖关系是
MyFragment
我对这段代码做错了什么请改正。
发布于 2020-07-29 13:49:54
首先,我认为在您的@Inject
类中缺少了RealFeature,因此Hilt知道如何注入依赖项。其次,如果您想要注入一个不属于Hilt支持的入口点的类,则需要为该类定义自己的入口点。
除了用@Provides
方法编写的模块之外,还需要告诉Hilt如何访问依赖项。
在您的情况下,您应该尝试这样的方法:
@EntryPoint
@InstallIn(ApplicationComponent::class)
interface FeatureInterface {
fun getFeatureClass(): Feature
}
然后,当您想使用它时,编写如下内容:
val featureInterface =
EntryPoints.get(appContext, FeatureInterface::class.java)
val realFeature = featureInterface.getFeatureClass()
您可以在这里找到更多信息:
https://dagger.dev/hilt/entry-points
https://developer.android.com/training/dependency-injection/hilt-android#not-supported
https://stackoverflow.com/questions/62826677
复制相似问题