如何使用Dagger 2将Context注入Presenter

时间:2018-01-21 06:30:08

标签: android dependency-injection kotlin dagger-2 dagger

我最近用新的Android注射器检查了Dagger 2.14.1。

我正在使用MVP并且Presenter正在正确地注入View:

class CustomApplication : Application(), HasActivityInjector {

    @Inject
    lateinit var activityDispatchingAndroidInjector: DispatchingAndroidInjector<Activity>

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

    override fun onCreate() {
        super.onCreate()
        DaggerApplicationComponent
                .builder()
                .create(this)
                .inject(this)
    }

    override fun activityInjector(): DispatchingAndroidInjector<Activity> {
        return activityDispatchingAndroidInjector
    }
}

-

@Singleton
@Suppress("UNUSED")
@Component(modules = arrayOf(AndroidInjectionModule::class, ApplicationModule::class, ActivityBuilder::class))
interface ApplicationComponent : AndroidInjector<CustomApplication> {

    @Component.Builder
    abstract class Builder : AndroidInjector.Builder<CustomApplication>()

    override fun inject(application: CustomApplication)
}

-

@Module
class ApplicationModule {

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

-

@Module
@Suppress("UNUSED")
abstract class ActivityBuilder {
    @ContributesAndroidInjector(modules = arrayOf(ActivitiesModule::class))
    internal abstract fun bindSplashActivity(): SplashActivity
}

-

@Singleton
class SplashPresenter @Inject constructor() {

    fun test() {
        Log.d("TAG", "this is a test")
    }
}

现在,我不想将记录的消息编码,我想从string.xml中获取它,所以我尝试了这个:

@Singleton
class SplashPresenter @Inject constructor(private val context: Context) {

    fun test() {
        Log.d("TAG", context.getString(R.strings.test))
    }
}

但后来我收到了这个错误:

  

错误:(7,1)错误:[dagger.android.AndroidInjector.inject(T)]   没有@Inject就无法提供android.app.Application   构造函数或来自@ Provide-annotated方法。

有人能告诉我如何将应用程序上下文(或资源)注入演示者吗?

感谢。

1 个答案:

答案 0 :(得分:3)

您在CustomApplication中使用ApplicationComponent与Dagger一起使用,以便知道它的内容。它并没有尝试自己解决类型,所以Application是Dagger从未听说过的类。

您可以添加其他@Provides / @Binds来绑定CustomApplication > Application > Context,也可以直接更改代码,以便CustomApplication代替Application }:

@Provides
@Singleton
fun provideContext(application: CustomApplication): Context {
    return application
}

  // ... or alternatively ...

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

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

无论哪种方式,您的应用程序都可以用作Context