我正在和Dagger打交道,我正在使用它的1.2版本,我有以下情况:
模块:
@Module(injects = {
AuthenticationService.class
})
public class ServiceModule {
@Provides
AuthenticationService provideAuthenticationService() {
return ServiceFactory.buildService(AuthenticationService.class);
}
}
在我的Application类中,我创建了ObjectGraph:
public class FoxyRastreabilidadeApplication extends Application {
private static FoxyRastreabilidadeApplication singleton;
@Override
public void onCreate() {
super.onCreate();
createObjectGraph();
singleton = this;
}
private void createObjectGraph() {
ObjectGraph.create(ServiceModule.class);
}
}
最后,在我的LoginActivity中,我尝试注入我的AuthenticationService:
public class LoginActivity extends Activity implements LoaderCallbacks<Cursor> {
private UserLoginTask mAuthTask = null;
@Inject
AuthenticationService authenticationService;
}
此时,当我尝试访问我的AuthenticationService实例时,它始终为null,这意味着它根本没有注入,我调试了我的提供程序方法以确保它,所以,问题是,我错过了什么吗?如果是这样,它是什么?
答案 0 :(得分:0)
您需要抓住ObjectGraph
并要求它直接注射您的物品。
Application
子类以保留创建的ObjectGraph
: this.objectGraph = ObjectGraph.create(ServiceModule.class);
Application
添加便捷方法进行注射: public void inject(Object object) {
this.objectGraph.inject(object);
}
Activity
: public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MyApplication)getApplication()).inject(this);
...
}