不能在Android上使用Dagger注入课程

时间:2015-04-08 04:24:55

标签: android dependency-injection dagger

我正在和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,这意味着它根本没有注入,我调试了我的提供程序方法以确保它,所以,问题是,我错过了什么吗?如果是这样,它是什么?

1 个答案:

答案 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); ... }