Inject database in a ContentProvider with dagger

前端 未结 5 2460
无人及你
无人及你 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:23

    based on @Mick answer and @LeEnot article I posted an article on Medium using new Dagger 2 features.

    https://medium.com/@pedro.henrique.okawa/content-providers-dependency-injection-dagger-2-4ee3e49777b

    But basically I put the Dagger-Android dependency:

    // In my case I used 2.16 version
    implementation 'com.google.dagger:dagger-android:[DaggerVersion]'
    

    Implemented my custom Application class with HasContentProviderInjector interface and changed to inject my dependencies on attachBaseContext:

    class App : Application(), HasActivityInjector, HasContentProviderInjector {
    
        @Inject
        lateinit var androidInjector: DispatchingAndroidInjector
    
        @Inject
        lateinit var contentProviderInjector: DispatchingAndroidInjector
    
        override fun activityInjector() = androidInjector
    
        override fun contentProviderInjector() = contentProviderInjector
    
        override fun attachBaseContext(base: Context?) {
            super.attachBaseContext(base)
            setupDependencyInjection()
        }
    
        /**
         * Injects the app component
         */
        private fun setupDependencyInjection() {
            DaggerAppComponent.builder().application(this).build().inject(this)
        }
    
    }
    

    And injected my databaseHelper instance on my ContentProvider class:

    class VoIPAppProvider: ContentProvider() {
    
        @Inject
        lateinit var databaseHelper: DatabaseHelper
    
        override fun onCreate(): Boolean {
            AndroidInjection.inject(this)
            return true
        }
    
        override fun insert(uri: Uri?, contentValues: ContentValues?): Uri? {
            ...
            return uri
        }
    
        override fun query(uri: Uri?, projection: Array?, selection: String?, selectionArgs: Array?, sortOrder: String?): Cursor {
            ...
            return cursor
        }
    
        override fun getType(uri: Uri?): String {
            ...
            return type
        }
        override fun update(uri: Uri?, contentValues: ContentValues?, selection: String?, selectionArgs: Array?): Int {
            ...
            return rowsUpdated
        }
    
        override fun delete(uri: Uri?, selection: String?, selectionArgs: Array?): Int {
            ...
            return rowsDeleted
        }
    }
    

    PS: I decided to not use DaggerContentProvider class because most of us may already have a base class for some Android components.

    I hope it help you and thanks again to @Mick and @LeEnot

提交回复
热议问题