【发布时间】:2021-01-11 21:08:45
【问题描述】:
我最近通过 Dagger Hilt 开始在我的项目中使用 DI。将实例注入活动、片段......等时我没有问题。但我不确定如何将类实例注入 ViewModel。
我目前的方法包括将我需要的类添加到视图模型的构造函数中:
class MainViewModel @ViewModelInject constructor(
application: Application,
@Named("classA") var classA: ClassA,
@Named("classB") var classB: ClassB
) : AndroidViewModel(application)
然后在我的 AppModule 中:
@Module
@InstallIn(ApplicationComponent::class)
object AppModule {
@Singleton
@Provides
@Named("ClassA")
fun provideClassA(@ApplicationContext context: Context) = ClassA(context)
@Singleton
@Provides
@Named("ClassB")
fun provideClassB(@ApplicationContext context: Context) = ClassB(context)
}
效果很好,但理想情况下,如果我想添加更多其他类的实例,我更愿意这样做
@Inject
lateinit var classA:ClassA
但我认为这是不可能的,因为不可能将@AndroidEntryPoint 添加到 viewModel,那么如何将类注入到 viewmodel 中?还是我们只是将它们添加到构造函数中,就像我当前的解决方案一样?
【问题讨论】:
标签: android kotlin dependency-injection dagger-hilt