Search code examples
androidkotlindagger-2dagger-hilt

Dagger/MissingBinding but module exists


I'm trying to put dagger into my project and I'm facing a compilation issue I don't get since I've done everything like the android developer tutorial. I get:

error: [Dagger/MissingBinding] INotificationService cannot be provided without an @Provides-annotated method

Here is my app annotation:

@HiltAndroidApp
class App : MultiDexApplication() {

Activity annotation:

@AndroidEntryPoint
class MainActivity: AppCompatActivity() {

Fragment annotation:

@AndroidEntryPoint
class NotificationFragment: Fragment(R.layout.fragment_notification) {

I think everything's ok until there. Then the problem I'm facing is here:

Viewmodel class:

@HiltViewModel
class NotificationViewModel @Inject constructor(private val notificationService: INotificationService): ViewModel()

Here is the interface for INotificationService:

interface INotificationService {
    fun refreshNotification(): Single<List<INotification>>
    fun markAsRead(notification: INotification)
}

and the implementation:

class NotificationServiceImpl @Inject constructor(@ApplicationContext context: Context): INotificationService

with associated module:

@Module
@InstallIn(ActivityComponent::class)
abstract class NotificationModule {
    @Binds
    abstract fun bindNotificationService(impl: NotificationServiceImpl): INotificationService
}

The bindNotificationService binds function from the module is greyed out, it's not the case on the android developer tutorial and the error makes me think I missed something to make this function findable at compile time but since there is @Module and @InstallIn(ActivityComponent::class) I have absolutly no idea why it doesn't compile.


Solution

  • INotificationService is ViewModel dependency and it should bind with ViewModel lifecycle so instead of this

    @Module
    @InstallIn(ActivityComponent::class)
    abstract class NotificationModule {
        @Binds
        abstract fun bindNotificationService(impl: NotificationServiceImpl): INotificationService
    }
    

    Use this:-

    @Module
    @InstallIn(ViewModelComponent::class)
    abstract class NotificationModule {
        @Binds
        abstract fun bindNotificationService(impl: NotificationServiceImpl): INotificationService
    }