我正在尝试使用Dagger2建立一个项目,但我可能误会了如何使用Dagger2。我有2个模块:app
包含我的应用程序代码,integration
包含与另一个库的集成。
app
模块具有一个定义的AppComponent
组件,该组件非常简单,只是为我的MyApplication
类定义了一个注入器。
integration
模块稍微复杂一点,包含一堆提供@Inject
构造函数和@AutoFactory
类的类:
public class MyController {
@Inject
MyController(MyInternalControllerFactory factory) {}
}
@AutoFactory
class MyInternalController {
MyInternalController(
@Provided FooInternalControllerFactory fooFactory,
@Provided ExternalController externalController,
int someOtherParam) {
...
}
}
@AutoFactory
class FooInternalController {
FooInternalController(@Provided LocalController, Listener listener) { ... }
}
class LocalController {
@Inject LocalController() {}
}
一切正常,直到我添加了ExternalController
,大概是因为它们都使用了@Inject
构造函数和@AutoFactory
注释。我意识到我必须为外部控制器编写一个提供程序,所以我这样做了:
@Module
class ExternalModule {
@Provides
static ExternalController() {
return new ExternalController();
}
}
@Component(modules = ExternalModule.class)
public interface ExternalComponent {}
然后我更新了AppComponent
,以允许将该组件设置为依赖项,并更新了应用程序的创建:
@Component(dependencies = ExternalComponent.class)
public interface AppComponent {
@Component.Builder
interface Builder {
@BindsInstance Builder applicationContext(Context applicationContext);
Builder externalComponent(ExternalComponent externalComponent);
}
}
public class MyApplication extends Application {
private AppComponent applicationComponent;
@Override
public void onCreate() {
super.onCreate();
applicationComponent = DaggerAppComponent
.builder()
.applicationContext(getApplicationContext())
.externalComponent(DaggerExternalComponent.create())
.build();
}
}
此操作失败,并显示一条错误消息,指出ExternalController
没有提供者或注入。如果我理解正确,这意味着我必须为一个从属模块连接所有模块?我是否必须构造ExternalComponent
并在其上设置ExternalModule
?
-
退一步,我使用这种方法的整个目标是在integration
中拥有一组实际驱动实现的包私有类。支持的一组公共API(在本例中为MyController
)将被允许注入我的app
模块中。不得不了解模块的实现细节是什么,并且必须将组件适当地连接到@Module
实现上,这似乎有点违反直觉。
任何帮助将不胜感激!