Dagger + Kotlin没有注射

时间:2016-11-22 12:09:08

标签: android dependency-injection kotlin dagger-2

我正在研究Dagger 2的DI,我只是做了这个代码来注入Retrofit:

NetModule.kt

@Module
class NetModule(val baseUrl: String) {

    @Provides
    @Singleton
    fun provideRetrofit() : Retrofit{
        [some logic here]
    }
}

AppModule.kt

@Module
class AppModule(val mApplication: Application) {

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

NetComponent.kt:

@Singleton
@Component(modules = arrayOf(AppModule::class, NetModule::class))
interface NetComponent {
    fun inject(activity: Activity)
}

CustomApplication.kt

class CustomApplication : Application() {

    companion object {
        lateinit var mNetComponent: NetComponent
    }

    override fun onCreate() {
        super.onCreate()

        AndroidThreeTen.init(this)

        mNetComponent = DaggerNetComponent.builder()
                            .appModule(AppModule(this))
                            .netModule(NetModule(getString(R.string.api_base_url)))
                            .build()

    }
}

然后在我的活动中:

class TrashCansInfoActivity : AppCompatActivity(){

@Inject
    lateinit var mRetrofit: Retrofit

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_trash_cans_info)

        CustomApplication.mNetComponent.inject(this)

        setSupportActionBar(toolbar)

        populateTrashCanList()

    }

    private fun populateTrashCanList(){
        showProgress(true)
        mRetrofit.create(ApiClient::class.java)
                .getTrashCans()
                .map { it.map { it.toTrashCan() } }
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnError {
                    showProgress(false)
                    Toast.makeText(this, "Erro ao carregar lista de lixeiras", Toast.LENGTH_SHORT).show()
                }.doOnCompleted { showProgress(false) }
                .subscribe(behaviorSubject)
    }

}

所以,这段代码应该可行,对吧?应该添加依赖...但是当我运行我的应用程序时......我明白了:

kotlin.UninitializedPropertyAccessException: lateinit property mRetrofit has not been initialized

因此没有注入Retrofit。我错过了什么?

欢迎任何帮助!

2 个答案:

答案 0 :(得分:19)

fun inject(activity: Activity)

应该是

fun inject(activity: TrashCansInfoActivity)

答案 1 :(得分:2)

我得到了同样的错误。 错误是 - 没有注入组件。此外,我不得不在片段中注入组件。 (在kotlin中)

  

val component =(activity?.application as MyApplication).appComponent       component.plus(FakeModule(本))。注射(本)

这解决了错误。