0

I am beggining with Dagger, I am using 1.2 version of it, and I have the following scenario:

Module:

@Module(injects = {
    AuthenticationService.class
})
public class ServiceModule {

    @Provides
    AuthenticationService provideAuthenticationService() {
        return ServiceFactory.buildService(AuthenticationService.class);
    }

}

On my Application class I create the 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);
     }
}

and finally, at my LoginActivity, I try to inject my AuthenticationService:

public class LoginActivity extends Activity implements LoaderCallbacks<Cursor> {

    private UserLoginTask mAuthTask = null;

    @Inject
    AuthenticationService authenticationService;
}

At this point, when I try to access my AuthenticationService instance it is always null, meaning it wasnt injected at all, I debugged my provider method to be sure of it, so, the question is, am I missing something? If so, what is it?

MrEngineer13
  • 38,642
  • 13
  • 74
  • 93
Marcos J.C Kichel
  • 6,887
  • 8
  • 38
  • 78

1 Answers1

0

You need to hold on to the ObjectGraph and ask it to inject your objects directly.

  • Add an instance variable to your custom Application subclass to hold on to the created ObjectGraph:

this.objectGraph = ObjectGraph.create(ServiceModule.class);

  • Add a convenience method to your Application to do injection:

public void inject(Object object) { this.objectGraph.inject(object); }

  • Call that method wherever you need injection to happen, for example in your Activity:

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((MyApplication)getApplication()).inject(this); ... }

bolot
  • 2,854
  • 2
  • 18
  • 15