Search code examples
androidroboguice

Injecting Android Application in Roboguice 3 creates a duplicate


When using Roboguice 3 I can see it behaves differently than version 2. When I have custom Application object:

public class MyApplication extends Application
{
    ...
}

then in another class:

@Inject
private MyApplication app;

This code injects another MyApplication object, not the one that was created during startup of the app. (Where in Roboguice2 this is not the case)

Binding:

public class InjectionModule extends AbstractModule
{
    @Override
    protected void configure()
    {
        bind(MyApplication.class).in(Singleton.class);
    }
}

does not change this behavior.

How can I add the global MyApplication object to the container?


Solution

  • You will need to create a Provider for that. In you module bind your class to the provider: bind(MyApplication.class).toProvider(ApplicationProvider.class);

    Your provider should look something like below: (haven't tested the code)

    public class ApplicationProvider implements Provider<MyApplication> {
        @Inject 
        Context context;
        @Override
        public MyApplication get() {
             return (MyApplication) context.getApplicationContext();
        }
     }