学习Dagger2并且可能会在这里脱轨。我有一个类 - 在片段中可能需要或可能不需要的MapRoute。如果需要MapRoute,我想创建它,当MapRoute被实例化时,我想用应用程序级别创建的依赖项注入它。我也使用Builder模式填充MapRouter。
也许通用的问题是当你在nonAndroid类(不是Activity / Fragment / ...)时如何从上面注入依赖项?如何构建nonAndroid注入器代替AndroidInjection.inject(this)?
所以我的片段是:
public class ActivityMapFragment extends DaggerFragment ... {
@Inject
MapRoute.Builder mapRouteBuilder;
private void plotRouteForMap(Cursor csr){
MapRoute.Builder builder = new MapRoute.Builder();
builder.setSupportMapFragment(supportMapFragment)
.setLocationExerciseRecord(ler)
.setMapType(mapType)
.setUseCurrentLocationLabel(useCurrentLocationLabel)
.setCursor(csr)
.setTitle(activityTitle)
.setActivityPhotosCallback(this);
mapRoute = builder.build();
mapRoute.plotGpsRoute();
}
...
MapRoute是:(编辑)添加了构建器代码段
public class MapRoute ... {
@Inject
public DisplayUnits displayUnits; <<< Created at app level
@Inject
public PhotoUtils photoUtils; <<<< Create at app level
public MapRoute() {
// Use subcomponent builder
MapRouteSubcomponent component =
DaggerMapRouteSubComponent.builder().build(); <<< Want to do this
component.inject(this);
}
public static class Builder {
SupportMapFragment supportMapFragment;
LocationExerciseRecord ler;
boolean useCurrentLocationLabel;
int mapType;
Cursor cursor;
ActivityPhotosCallback activityPhotosCallback;
String title;
@Inject
public Builder() {
}
public Builder setSupportMapFragment(SupportMapFragment supportMapFragment){
this.supportMapFragment = supportMapFragment;
return this;
}
....
MapRouteSubcomponent最佳猜测:
@Subcomponent(modules = {MapRouteModule.class, ApplicationModule.class})
public interface MapRouteSubcomponent {
// allow to inject into our MapRoute class
void inject(MapRoute mapRoute);
@Subcomponent.Builder
interface Builder extends SubComponentBuilder<MapRouteSubcomponent> {
Builder mapRouteModule(MapRouteModule mapRouteModule);
}
@Module
public class MapRouteModule {
// What to put here?
}
最后是一个子组件构建器:
// from https://github.com/Zorail/SubComponent/blob/master/app/src/main/java/zorail/rohan/com/subcomponent/SubComponentBuilder.java
public interface SubComponentBuilder<V> {
V build();
}
此时我站在离开这里的地方。