匕首2出现问题

时间:2019-12-05 11:39:32

标签: android kotlin dagger

您好,我在此配置中的项目中使用的是匕首2。

这是我的SellerHubApplication.kt

class SellerHubApplication : Application(), HasAndroidInjector {

@Inject
lateinit var activityDispatchingAndroidInjector: AndroidInjector<Any>

override fun androidInjector(): AndroidInjector<Any> = activityDispatchingAndroidInjector

override fun onCreate() {
    super.onCreate()

    DaggerAppComponent.builder()
        .application(this)
        .build()
        .inject(this)

    Fresco.initialize(applicationContext)
}

}

这是我的AppComponent.kt

@Singleton
@Component(modules = [AndroidInjectionModule::class, ActivityBuilder::class, AppModule::class])
interface AppComponent {

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(app: Application): Builder

        fun build(): AppComponent
    }

    fun inject(app: SellerHubApplication)

}

运行应用程序后,出现以下错误“错误:[Dagger / MissingBinding] dagger.android.AndroidInjector如果没有@Provides注释的方法,将无法提供。”

如果我将“ fun inject(app:SellerHubApplication)”更改为“ fun inject(app:Application)”,则应用程序会运行,但会显示“ activityDispatchingAndroidInjector尚未初始化”。请帮助我。

1 个答案:

答案 0 :(得分:2)

尝试这样做:

AppComponent:

@Singleton
@Component(modules = [AndroidInjectionModule::class, ActivityBuilder::class, AppModule::class, FragmentBuilder::class,])
interface AppComponent : AndroidInjector< SellerHubApplication > {

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(application: SellerHubApplication): Builder

        fun applicationModule(applicationModule: AppModule): Builder
        fun build(): AppComponent
    }
}

应用程序:

class SellerHubApplication : Application(), HasActivityInjector, HasSupportFragmentInjector {

    @Inject
    lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity>

    @Inject
    lateinit var fragmentInjector: DispatchingAndroidInjector<Fragment>


    companion object {
        lateinit var applicationComponent: AppComponent
            private set
    }


    override fun onCreate() {
        super.onCreate()

        init()
    }

    override fun activityInjector(): AndroidInjector<Activity> {
        return dispatchingAndroidInjector
    }

    override fun supportFragmentInjector(): AndroidInjector<Fragment> {
        return fragmentInjector
    }


    private fun init() {
        initDagger()
    }

    private fun initDagger() {
        applicationComponent = DaggerAppComponent
                .builder()
                .application(this)
                .applicationModule(AppModule(this))
                .build()

        applicationComponent.inject(this)
    }

}

AppModule:

@Module
class AppModule(private val application: SellerHubApplication) {

    @Provides
    @Singleton
    fun provideApplication(): Application {
        return application
    }
}