首页 > 解决方案 > 为什么 Dagger Factory 方法不像 Builder 那样工作?

问题描述

在我的 Android 项目和app模块中,我有一个登录屏幕。我想通过匕首提供它的视图模型。但是,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
    }
}

应用程序在上面的标记行崩溃,因为 logger 是null. 我调试了应用程序并注意到 ViewModel 也为空。

标签: androiddagger-2

解决方案


我不知道究竟是什么问题,但我用 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)
}

推荐阅读