简体   繁体   中英

Kotlin: Dagger2 @Inject context var is always null

I am trying to to do module in AndroidStudio which is not connected with Android, it has no Activities, but i need Context for several things like Room database.

Here is my setup:

AppComponent

@Singleton
@Component(modules = arrayOf(AndroidSupportInjectionModule::class, AppModule::class))
interface AppComponent : AndroidInjector<NexoApplication> {

@Component.Builder
interface Builder {
    @BindsInstance
    fun application(application: NexoApplication): Builder
    fun build(): AppComponent
 }

override fun inject(app: NexoApplication)
}

AppModule

@Module
class AppModule {
@Singleton @Provides
fun provideLogger(application: NexoApplication) = LogNexoManager(application)
}

AppLifecycleCallbacks

interface AppLifecycleCallbacks {
fun onCreate(application: Application)
fun onTerminate(application: Application)
}

App

class NexoApplication: DaggerApplication() {

@Inject lateinit var appLifecycleCallbacks: AppLifecycleCallbacks

override fun applicationInjector() = DaggerAppComponent.builder()
        .application(this)
        .build()

override fun onCreate() {
    super.onCreate()
    appLifecycleCallbacks.onCreate(this)
}

override fun onTerminate() {
    appLifecycleCallbacks.onTerminate(this)
    super.onTerminate()
   }

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.elstatgroup.elstat">

<application
    android:name="com.elstatgroup.elstat.NexoApplication"
    android:allowBackup="true"
    android:label="@string/app_name"
    android:supportsRtl="true">
</application>

And i try to inject context to my main class like this:

class LogNexoManager(app: Application){
   var logRepository: LogRepository


init {
    logRepository = LogRepositoryImpl(app)

 }
}

Sample unit test is always false

   @Test
fun proceedWithLogs(){
    val logManager = LogManager()
}

And the exception is:

kotlin.UninitializedPropertyAccessException: lateinit property app has not been initialized

UPDATE: I made the changes proposed by @Emanuel S and now i have an error like:

Error:Execution failed for task ':nexo:kaptDebugKotlin'. Internal compiler error. See log for more details

My Build.gradle file is:

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

android {
compileSdkVersion 26

defaultConfig {
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

}

ext.daggerVersion = '2.11'
ext.roomVersion = '1.0.0-alpha9'

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

// RxJava
implementation 'io.reactivex.rxjava2:rxjava:2.1.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'

// Room
implementation "android.arch.persistence.room:runtime:$roomVersion"
implementation "android.arch.persistence.room:rxjava2:$roomVersion"
kapt "android.arch.persistence.room:compiler:$roomVersion"
compile "org.jetbrains.kotlin:kotlin-stdlib:1.1.51"


androidTestImplementation "android.arch.persistence.room:testing:$roomVersion"

compile "com.google.dagger:dagger:$daggerVersion"
compile "com.google.dagger:dagger-android:$daggerVersion"
compile "com.google.dagger:dagger-android-support:$daggerVersion"
kapt "com.google.dagger:dagger-android-processor:$daggerVersion"
kapt "com.google.dagger:dagger-compiler:$daggerVersion"
implementation "com.google.dagger:dagger-android-support:2.11-rc2" // version may be not up 2 date later.
}

repositories {
mavenCentral()
}

Here's a simple test case. Not tested but should show the concept how you should inject into your LogManager.

@Singleton
@Component(modules = arrayOf(AndroidSupportInjectionModule::class, AppModule::class))
interface AppComponent : AndroidInjector<App> { {

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(application: App): Builder
        fun build(): AppComponent
    }

    override fun inject(app: App)
}

@Module
class AppModule {

    @Singleton @Provides
    fun provideYourDb(application: App) = Room.databaseBuilder(application, YourDb::class.java, "your.db").build()

    @Singleton @Provides
    fun provideLogger(application: App) = LogManager(application)
}

An interface for the Apps lifecycle.

interface AppLifecycleCallbacks {
   fun onCreate(application: Application)
   fun onTerminate(application: Application)
}

Your application should extend DaggerApplication().

class App:DaggerApplication() {

    @Inject lateinit var appLifecycleCallbacks: AppLifecycleCallbacks

    override fun applicationInjector() = DaggerAppComponent.builder()
            .application(this)
            .build()

    override fun onCreate() {
        super.onCreate()
        appLifecycleCallbacks.onCreate(this)
    }

    override fun onTerminate() {
        appLifecycleCallbacks.onTerminate(this)
        super.onTerminate()
    }

}

finally you have a provided LogManager.

class LogManager (val app: App)    

If you really want to use @Inject inside your LogManager you can inject it inside your AppComponent using fun inject(logManager: LogManager) .

The lifecycle interface is used for auto injection of activities/services in case you want to extend it later. Example:

App entry class

override fun onCreate() {
     super.onCreate()
     applyAutoInjector()
     appLifecycleCallbacks.onCreate(this)
}


fun Application.applyAutoInjector() = registerActivityLifecycleCallbacks(
        object : Application.ActivityLifecycleCallbacks {

            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                handleActivity(activity)
            }
         //truncated ... 
        })

Take care that you need the dependencies for dagger-android-support in your gradle to have AndroidSupportInjectionModule.

implementation "com.google.dagger:dagger-android-support:2.11-rc2" // version may be not up 2 date later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM