Two @Injects in one object but from two different Components

北城以北 提交于 2019-12-25 08:25:27

问题


I have:

@Inject
AdalService adalService;

@Inject
Realm realm;

Both of these come from two different Components.

AdalComponent

@UserScope
@Component(dependencies = {NetComponent.class}, modules = AdalServiceModule.class)
public interface AdalServiceComponent
{
    void inject(MainActivity activity);

    void inject(EventsJob eventsJob);
}

RealmComponent

@UserScope
@Subcomponent(modules = RealmModule.class)
public interface RealmComponent
{
    void inject(EventsJob eventsJob);
}

But I get the following error:

Error:(16, 10) error: io.realm.Realm cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method.
    io.realm.Realm is injected at
    com.bjss.bjssevents.jobs.EventsJob.realm
    com.bjss.bjssevents.jobs.EventsJob is injected at
    com.bjss.bjssevents.dagger.components.AdalServiceComponent.inject(eventsJob)

RealmModule

@Module
public class RealmModule
{
    private static final String TAG = RealmModule.class.getSimpleName();

    public RealmModule(@Singleton final Context context)
    {
        Log.d(TAG, "Configuring Realm");
        Realm.init(context);
        Realm.setDefaultConfiguration(new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build());
    }

    @UserScope
    @Provides
    public Realm providesRealm()
    {
        Log.d(TAG, "Providing Realm");
        return Realm.getDefaultInstance();
    }
}

回答1:


Inside AdalServiceComponent and RealmComponent you have the same method:

void inject(EventsJob eventsJob);

That is unacceptable. The must be only one inject method for specified object (argument of inject method).

Also you can't inject things from two moduled at the same level. Both Component's are annotated with the same Scope: @UserScope. They don't know nothing about each other. If you want to define resources in AdalServiceComponent and RealmComponent make one of them parent Component and the other one Subcomponent. And the inject method should be in subcomponent.

Please read this excellent article series about advanced Dagger-2 behaviour to gain better understanding of this library.



来源:https://stackoverflow.com/questions/40632408/two-injects-in-one-object-but-from-two-different-components

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!