Ari
Ari

Reputation: 1316

Not able to inject a class using SubComponent in Dagger 2

I'm trying to add Dagger 2 in one project. I have created 3 components

AppComponent (the primary one)
RetrofitComponent (Dependent component works fine)
ControllerComponent (Subcomponent, not injecting properly)

this is my AppComponent

@ApplicationScope
@Component(modules = [ApplicationModule::class, PrefModule::class])
interface AppComponent {

fun inject(instance: AppInstance)

fun getAppPref(): AppPreference

fun newControllerComponent(controllerModule: ControllerModule): ControllerComponent
}

this is my ControllerComponent

@UIScope
@Subcomponent(modules = [ControllerModule::class])
interface ControllerComponent {

fun injectActivity(activity: BaseActivity)

fun injectDialog(dialog: BaseDialog)
}

ControllerModule

@Module
class ControllerModule(activity: FragmentActivity) {
var mActivity: FragmentActivity

init {
    mActivity = activity
}

@Provides
fun getContext(): Context {
    return mActivity
}

@Provides
fun getActivity(): Activity {
    return mActivity
}

@Provides
fun getFragmentManager(): FragmentManager {
    return mActivity.supportFragmentManager
}

@Provides
fun getDialogManager(fragmentManager: FragmentManager): DialogsManager 
{
    return DialogsManager(fragmentManager)
}

@Provides
fun getDialogsFactory(): DialogsFactory {
    return DialogsFactory()
}

}

Injecting the activity is working fine, but when I try to inject the Dialog its never injecting

 controller.injectDialog(singleDialog)

My entire code is here Github link. Need some help. What am I not doing or doing wrong that I can't inject from subcomponent.

Upvotes: 0

Views: 291

Answers (2)

EpicPandaForce
EpicPandaForce

Reputation: 81578

To use field injection on a given class, you need to specify the concrete type rather than its superclass.

@UIScope
@Subcomponent(modules = [ControllerModule::class])
interface ControllerComponent {

    //fun injectActivity(activity: BaseActivity)

    //fun injectDialog(dialog: BaseDialog)

    fun inject(activity: SomeSpecificActivity)

    fun inject(activity: SomeOtherActivity)

    fun inject(dialog: SomeSpecificDialog)

    fun inject(dialog: SomeOtherDialog)
}

Upvotes: 2

Bonestack
Bonestack

Reputation: 81

The Injection is working, but you are injecting nothing inside SingleClickDialog class, remember than the method inject(class : Class) is for let it to know dagger that class will be injected, but you need to put the elements you need inject inside that class with the annotation @Inject, and those elements you need to add its provider in ControllerModule as well

Upvotes: 0

Related Questions