在一个对象中来自两个不同组件的两个@Injects [英] Two @Injects in one object but from two different Components
问题描述
我有:
@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);
}
但是出现以下错误:
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();
}
}
推荐答案
内部 AdalServiceComponent
和 RealmComponent
您具有相同的方法:
Inside AdalServiceComponent
and RealmComponent
you have the same method:
void inject(EventsJob eventsJob);
这是不可接受的。对于指定对象,该对象只能是一个 inject
方法(参数 inject
的参数)。
That is unacceptable. The must be only one inject
method for specified object (argument of inject
method).
此外,您不能从同一级别的两个模块中注入东西。两个 Component
都具有相同的范围: @UserScope
。他们彼此一无所知。如果要在 AdalServiceComponent
和 RealmComponent
中定义资源,请使其中之一成为父级 Component
和另一个 Subcomponent
。并且 inject
方法应该在子组件中。
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.
请阅读这本关于高级Dagger-2行为的优秀文章系列,以更好地理解该库。
Please read this excellent article series about advanced Dagger-2 behaviour to gain better understanding of this library.
这篇关于在一个对象中来自两个不同组件的两个@Injects的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!