0

I try to use Dagger2 to my project. I have a Firebase service and a class called SyncFactory that makes a specific request. When i get a call from Firebase i make my request. I have created a Mangers Module

@Module(includes = [RepositoryModule::class, NetworkModule::class, AppModule::class])
class ManagersModule {
...
    @Singleton
    @Provides
    fun provideSyncFactory(context: Context, accountsRepository: AccountsRepository, messagesRepository: MessagesRepository) : SyncFactory {
        return SyncFactory(context, accountsRepository, messagesRepository)
    }
...

}

The SyncFactory class is like below

class SyncFactory @Inject constructor(
    private val context: Context,
    private val accountsRepository: AccountsRepository,
    private val messagesRepository: MessagesRepository
) {

fun getAccounts(){....}

and i also have an interface

@Singleton
@Component(modules = [ViewModelsModule::class, DatabaseModule::class, RepositoryModule::class, AppModule::class, NetworkModule::class, ManagersModule::class])
interface ViewModelComponent {
    fun inject(viewModels: ViewModels)

    fun inject(firebaseService: AppFirebase)
}

And finally inside my firebase service i Inject the SyncFactory

class AppFirebase : FirebaseMessagingService(), SyncFactoryCallback {

    @Inject
    lateinit var syncFactory: SyncFactory


override fun onMessageReceived(message: RemoteMessage) {
    super.onMessageReceived(message)

    // lateinit property syncFactory has not been initialized
    syncFactory.getAccounts()

}

And when my service gets called i get a lateinit property syncFactory has not been initialized exception. What do i do wrong..?

james04
  • 1,580
  • 2
  • 20
  • 46
  • 1
    you dont inject your service with DaggerViewModelComponent – shadow Jan 03 '20 at 10:24
  • 1
    If you use `@Singleton class SyncFactory @Inject constructor(` then you can remove `provideSyncFactory` entirely. Otherwise, you should be using `@Binds` instead of `@Provides` to make it a `@Singleton`. – EpicPandaForce Jan 03 '20 at 10:28
  • What do you mean that i dont Inject my service? I am a newbie...can u explain plz? – james04 Jan 03 '20 at 10:48
  • you are missing `yourComponentInstance.inject(this)` in AppFirebase (probably the best place is in its `onCreate` – crgarridos Jan 04 '20 at 16:31

1 Answers1

0

The solution is to implement a HasServiceInjector in your Application class


class MyApplication : Application(), HasServiceInjector {

    @Inject
    lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Service>


    companion object {
        private lateinit var instance: MyApplication

    }


    override fun serviceInjector(): AndroidInjector<Service> {
        return dispatchingAndroidInjector
    }
}


james04
  • 1,580
  • 2
  • 20
  • 46