【发布时间】:2017-02-28 10:44:15
【问题描述】:
我已经开始设置 Dagger 2,遇到了一个奇怪的问题,对我来说似乎是一个错误。
我有 1 个主要组件和 2 个子组件,我在父组件中“加号”。我为每个子组件使用不同的scopes。问题是我可以轻松地为第一个子组件进行字段注入,但我不能为第二个子组件做同样的事情。注入的字段保持nulls。
主要组件:
@Singleton
@Component(modules = { WalletSaverAppModule.class })
public interface MyAppComponent {
TrackingComponent plus(TrackingModule module);
DashboardComponent plus(DashboardModule module);
}
第一个子组件(运行良好):
@PerActivity @Subcomponent(modules = { DashboardModule.class })
public interface DashboardComponent {
void inject(MainActivity activity);
}
第二个子组件(字段注入 -> null):
@PerService @Subcomponent(modules = { TrackingModule.class })
public interface TrackingComponent {
void inject(IntentService context);
}
我如何为第二个子组件进行字段注入:
public class TrackingService extends IntentService {
@Inject CallCase mCallCase;
@Inject CallModelMapper mCallModelMapper;
...
@Override protected void onHandleIntent(Intent intent) {
((MyApp) getApplication()).getAppComponent().plus(new TrackingModule(this)).inject(this);
// ---> here the both fields are null
...
我正在注入的对象:
@Singleton public class CallCase {
private CallRepository mCallRepository;
@Inject public CallCase(final CallRepository userRepository) {
mCallRepository = userRepository;
}
public Observable<Call> execute() {
...
}
}
@Singleton public class CallModelMapper {
@Inject CallModelMapper() {
}
public CallModel transform(@NonNull final Call callEntity) {
...
}
}
两个对象都有@Singleton 范围(作为它们的构造函数字段)。会不会是范围冲突?
--- 更新 ---
我检查了 Dagger2 (DaggerMyAppComponent) 生成的类,我在 MyApp 中使用它来构建应用程序组件。我发现了第一个和第二个组件的实现之间的区别。
第一个:
private final class DashboardComponentImpl implements DashboardComponent {
private final DashboardModule dashboardModule;
private Provider<DashboardMvp.Presenter> providesPresenterProvider;
private MembersInjector<MainActivity> mainActivityMembersInjector;
private DashboardComponentImpl(DashboardModule dashboardModule) {
this.dashboardModule = Preconditions.checkNotNull(dashboardModule);
initialize();
}
private void initialize() {...}
@Override
public void inject(MainActivity activity) {...}
}
第二个:
private final class TrackingComponentImpl implements TrackingComponent {
private final TrackingModule trackingModule;
private TrackingComponentImpl(TrackingModule trackingModule) {
this.trackingModule = Preconditions.checkNotNull(trackingModule);
// ---> look, missing call initialize() <---
}
@Override
public void inject(IntentService context) {...}
}
为什么 Dagger 2 采用了不同的以相同方式实现的子组件?我能看到的只有一个区别是范围。我将不胜感激有关此问题的任何意见。
提前致谢!
【问题讨论】:
-
如果将 TrackingComponent 的作用域更改为 PerActivity 会发生什么?
标签: java android dependency-injection dagger-2