Can`t inject dependencies in service with Dagger
Spent a lot of time on finding solution for this question, but all answers is a bit old (2018-2019) and cant be implementend in that way as in answers.
Now my code is:
AppComponent
@Singleton
@Component(
modules = [AndroidInjectionModule::class, DomainModule::class, DataModule::class, AppModule::class, ServiceModule::class]
)
interface AppComponent {
fun inject(app: Application)
fun inject(mainActivity: MainActivity)
fun inject(networkService: NetworkService)
}
Application class
class App : Application(), HasAndroidInjector {
lateinit var appComponent: AppComponent
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Any>
override fun onCreate() {
super.onCreate()
appComponent = DaggerAppComponent
.builder()
.appModule(AppModule(context = this))
.build()
appComponent.inject(this)
}
override fun androidInjector(): AndroidInjector<Any> {
return dispatchingAndroidInjector
}
}
NetworkService
class NetworkService : Service() {
@Inject
val someDependency:SomeDependency
override fun onCreate() {
super.onCreate()
Log.e(TAG, "Service create")
AndroidInjection.inject(this)
}
}
ServiceModule
@Module
abstract class ServiceModule {
@ContributesAndroidInjector
abstract fun contributeNetworkService(): NetworkService
}
I providing context in AppModule
@Module
class AppModule(val context: Context) {
@Provides
fun provideContext(): Context {
return context
}
}
At this moment app crashes with this exception:
java.lang.RuntimeException: Unable to create service com.xxx.xxx.service.NetworkService: kotlin.UninitializedPropertyAccessException: lateinit property dispatchingAndroidInjector has not been initialized
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property dispatchingAndroidInjector has not been initialized
at com.xxx.xxx.app.App.getDispatchingAndroidInjector(App.kt:18)
at com.xxx.xxx.app.App.androidInjector(App.kt:34)
at dagger.android.AndroidInjection.inject(AndroidInjection.java:177)
at dagger.android.AndroidInjection.inject(AndroidInjection.java:130)
at com.xxx.xxx.service.NetworkService.onCreate(NetworkService.kt:78)
Tried a lot of different solutions but they was too old and some classes is deleted at this moment. I tried to do something that will looks like solutions but this with no success