Inject database in a ContentProvider with dagger

前端 未结 5 2458
无人及你
无人及你 2021-02-19 22:57

I want to inject a singleton SqliteOpenHelper in a ContentProvider. However, it seems that the ContentProvider instance is being built bef

5条回答
  •  借酒劲吻你
    2021-02-19 23:17

    I know the question has an answer already but I post my experience hope this helps someone

    I added a module named ContentProviderBuilder :

    @Module
    abstract class ContentProviderBuilder {
    
    @ActivityScope
    @ContributesAndroidInjector
    abstract fun myCustomSuggestionProvider(): MyCustomSuggestionProvider?
    }
    

    then I added this module to my component, and extended the contentProvider from DaggerContentProvider

    and you have to add super.onCreate to your cotnentProvider and that's it

    this is my component:

    @Singleton
    @ApplicationScope
    @Component(modules = [AppModule::class, AndroidSupportInjectionModule::class, 
    RemoteModule::class, ContentProviderBuilder::class, ActivityBuilder::class, 
    FragmentBuilder::class, ViewModelModule::class])
    interface ApplicationComponent: AndroidInjector {
    
    @Component.Builder
    interface Builder {
    
        @BindsInstance
        fun application(application: MyApplication): Builder
    
        fun build(): ApplicationComponent
    }
    
    override fun inject(app: MyApplication)
    }
    

提交回复
热议问题