我真的想在我的应用中实现Dagger,但我很难理解应该如何正确配置它。 我有两个课我想注入。
public class LoginController {
@Inject Bus bus;
@Inject Context context;
// more code
}
public class LoginFragment {
@Inject Bus bus;
// more code
}
如果我将所有代码放在一个模块中,它可以正常工作:
@Module(injects = {LoginController.class, LoginFragment.class})
public class BasicModule {
@Provides
@Singleton
public Bus busProvider() {
return new Bus();
}
@Provides
public Context provideContext() {
return RblMobileApp.getContext();
}
}
但是当我将这些方法放在两个不同的模块(BasicModule和TestModule)中时,我遇到编译器错误:
@Module(injects = {LoginController.class, LoginFragment.class})
public class BasicModule {
@Provides
@Singleton
public Bus busProvider() {
return new Bus();
}
}
Error:(18, 8) java: No injectable members on android.content.Context. Do you want to add an injectable constructor? required by rblmobile.controllers.LoginController for rblmobile.injection.BasicModule
@Module(injects = {LoginController.class})
public class TestModule {
@Provides
public Context provideContext() {
return RblMobileApp.getContext();
}
}
Error:(13, 8) java: No injectable members on com.squareup.otto.Bus. Do you want to add an injectable constructor? required by rblmobile.controllers.LoginController for rblmobile.injection.TestModule
所以基本上我被告知BasicModule没有发送上下文而TestModule没有发送总线。为什么ObjectGraph不知道相应的构造函数在另一个模块中?
由于
编辑: 这就是创建ObjectGraph的方法。
public static void init(final Object... modules) {
Log.i(TAG, "initializing object graph");
if (objectGraph == null) {
objectGraph = ObjectGraph.create(modules);
} else {
objectGraph = objectGraph.plus(modules);
}
}
答案 0 :(得分:0)
有一个名为complete的@Module
注释属性。尝试将其设置为false
:
@Module(complete = false, injects = {LoginController.class, LoginFragment.class})
public class BasicModule {
@Provides
@Singleton
public Bus busProvider() {
return new Bus();
}
}
@Module(complete = false, injects = {LoginController.class})
public class TestModule {
@Provides
public Context provideContext() {
return RblMobileApp.getContext();
}
}