Android 为什么匕首工厂法不能像建造者那样工作?
在我的Android项目和我的Android 为什么匕首工厂法不能像建造者那样工作?,android,dagger-2,Android,Dagger 2,在我的Android项目和我的应用程序模块中,我有一个登录屏幕。我想通过dagger提供它的视图模型。然而,它总是null,尽管我清楚地定义了如何在模块类中生成它。这是我的代码: class AuthViewModel( private val firebaseAuth: FirebaseAuth, private val logger: Logger ) { .... } 这是模块对象 @Module object AuthModule {
应用程序
模块中,我有一个登录屏幕。我想通过dagger提供它的视图模型。然而,它总是null
,尽管我清楚地定义了如何在模块类中生成它。这是我的代码:
class AuthViewModel(
private val firebaseAuth: FirebaseAuth,
private val logger: Logger
) {
....
}
这是模块对象
@Module
object AuthModule {
@Provides
@JvmStatic
fun provideLogger(): Logger = getLogger() // It creates a Logger object forsure. I confirm it doesn't return null.
@Provides
@JvmStatic
fun provideViewModel(firebaseAuth: FirebaseAuth, logger: Logger) = AuthViewModel(firebaseAuth, logger)
@Provides
@JvmStatic
fun provideFirebaseAuth() = FirebaseAuth.getInstance()
}
这是组件
@FeatureScope
@Component(modules = [AuthModule::class])
interface AuthComponent {
@Component.Factory
interface Factory {
fun create(
@BindsInstance context: Context
): AuthComponent
}
}
这就是我如何将它注入到我的活动中
class AuthActivity : AppCompatActivity() {
@Inject lateinit var vm: AuthViewModel
@Inject lateinit var logger: Logger
companion object {
private val TAG = AuthActivity::class.java.simpleName
fun startActivity(ctx: Context) {
val intent = Intent(ctx, AuthActivity::class.java)
ctx.startActivity(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DaggerAuthComponent.factory()
.create(this)
logger.logDebug("test") // <==== Crashes here because logger is null
}
}
类AuthActivity:AppCompatActivity(){
@注入lateinit var vm:AuthViewModel
@注入lateinit变量记录器:记录器
伴星{
private val TAG=AuthActivity::class.java.simpleName
趣味星际触觉(ctx:Context){
val intent=intent(ctx,AuthActivity::class.java)
ctx.星触觉(意图)
}
}
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
DaggerAuthComponent.factory()
.创建(此)
logger.logDebug(“test”)/我不知道到底是什么问题,但我用Builder替换了Factory并修复了我的问题 欢迎您告诉我我的原始代码中有什么问题,我将非常乐意接受您的回答。谢谢
@FeatureScope
@Component(modules = [AuthModule::class])
interface AuthComponent {
@Component.Builder
interface Builder {
fun build(): AuthComponent
@BindsInstance fun activity(context: Context): Builder
}
fun inject(activity: AuthActivity)
}
您从未在原始版本中实际调用过
inject(this)
example@EpicPandaForce,你知道,有时候我扮演白痴的角色演得很好,这是我的杰作。我刚刚测试过,你是对的。如果你回答我的问题,我会非常乐意接受你的评论。谢谢。