Subby
Subby

Reputation: 5480

Two @Injects in one object but from two different Components

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();
    }
}

Upvotes: 0

Views: 82

Answers (1)

R. Zagórski
R. Zagórski

Reputation: 20258

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.

Upvotes: 2

Related Questions