Search code examples
androiddependenciescode-injectiondaggerdagger-hilt

Android dagger hilt


I have one class NavigationController which requires an activity instance all of my fragment are hosted through these activity.

class NavigationController constructor(private val activity: MainActivity) {
    
    fun navigateToAuth() {
        activity.supportFragmentManager
            .beginTransaction()
            .replace(R.id.main_container,WelcomeFrag())
            .commitAllowingStateLoss()
    }
}

And here is my NavigationModule

@InstallIn(ApplicationComponent::class)

@Module
object NavigationModule {
    @Provides
    fun providesNavigationModule(activity: MainActivity): NavigationController {
        return NavigationController(activity)
    }
}

But i'm getting Error as MainActivity cannot be provided requires @Inject or @Provides I know dagger doesnt know how to create MainActivity as it doesnt have constructor i cannot inject it

So how could i get activity and pass it to my NavigationController ?


Solution

    1. If your NavigationModule depends on the Activity, you're installing it in the wrong component. You should be using @InstallIn(ActivityComponent::class).
    2. Within the Activity scope (===ActivityComponent) Hilt can provide an instance of an Activity as a dependency. It cannot provide an instance of your exact MainActivity. It's hard to judge just from your code samples if this can fulfill your needs, but you might get away with simply:
    @InstallIn(ActivityComponent::class)
    @Module
    object NavigationModule {
        @Provides
        fun providesNavigationModule(activity: Activity): NavigationController {
            return NavigationController(activity)
        }
    }