Android Dagger 2 Injection For Fragment (Kotlin)

May 14, 2018

Refer to Setup Dagger 2 For Android Kotlin for general Dagger 2 setup with Activity, while this article shall focus on dependency injection in Fragment only.

NOTE: This article depends on classes declared in Setup Dagger 2 For Android Kotlin.

Application Class

Add HasSupportFragmentInjector and fragmentInjector to Application class.

class LuaApp : Application(), HasActivityInjector, HasSupportFragmentInjector {
    lateinit var activityInjector: DispatchingAndroidInjector<Activity>

    lateinit var fragmentInjector: DispatchingAndroidInjector<Fragment>

    override fun onCreate() {
        // initialize Dagger

    override fun activityInjector(): AndroidInjector<Activity> = activityInjector

    override fun supportFragmentInjector(): AndroidInjector<Fragment> = fragmentInjector

NOTE: If the above is not configured properly, you will bump into exception Caused by: java.lang.IllegalArgumentException: No injector was found for ... when AndroidSupportInjection.inject is called in Fragment.


Create FragmentModule class to declare Fragment for injection.

abstract class FragmentModule {
    internal abstract fun contributePhotoPinListFragment(): PhotoPinListFragment


Edit AppComponent to include @Component(modules = [..., (FragmentModule::class)])

@Component(modules = [(AndroidInjectionModule::class), (AppModule::class), (ActivityModule::class), (FragmentModule::class)])
interface AppComponent {
    interface Builder {
        fun application(application: Application): Builder

        fun build(): AppComponent

    fun inject(luaApp: LuaApp)


Include AndroidSupportInjection.inject at Fragment.onAttach.

Access ViewModel at Fragment.onActivityCreated.

class PhotoPinListFragment : Fragment() {

    lateinit var viewModelFactory: ViewModelFactory
    private lateinit var viewModel: PhotoPinListViewModel

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        viewModel = ViewModelProviders.of(this, viewModelFactory).get(

    override fun onAttach(context: Context) {


Remember to declare PhotoPinListViewMode at ViewModelModule.

internal abstract class ViewModelModule {
    abstract fun bindMainViewModel(viewModel: MainViewModel): ViewModel

    abstract fun bindPhotoPinListViewModel(viewModel: PhotoPinListViewModel): ViewModel


This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.