Dagger 2, Providing Application Context in Module

前端 未结 4 1326
北海茫月
北海茫月 2021-01-13 22:17

Im pretty new in Android development and newer in DI. I am using Kotlin on a personal project where I am experimenting with Dagger 2. I managed to set it up for a util class

4条回答
  •  醉酒成梦
    2021-01-13 22:58

    This is how It is done. Using @BindsInstance in your component will inject application to all of your modules.In your case just to AppModule

    @Singleton
    @Component(modules = arrayOf(AppModule::class))
    interface AppComponent {
        @Component.Builder
        interface Builder() {
            fun build(): AppComponent
    
            @BindsInstance
            fun application(application: Application): Builder
        }
    }
    

    ** Delete code to "Provides application" function in your APP module and make sure you pass application context to create sharedPreferences.

    @Module
    class AppModule {
    
    
    @Provides
    @Singleton
    fun provideSharedPrefManager(context: Application): SharedPreferencesManager = 
        SharedPreferencesManager(context)
    }
    

    and now in your onCreate of applicationClass

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

    Optional: if you want to inject something into your applicationClass then do the following

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

提交回复
热议问题