0

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?

Piotr Trzpil
  • 282
  • 2
  • 12

1 Answers1

1

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();
    }
 }
Jeroen
  • 3,399
  • 1
  • 22
  • 25
  • Haven't tested that, but I think it just moves the problem to the Context class. Should I bind MyApplication to Context? – Piotr Trzpil Oct 09 '13 at 13:30
  • No because the Context has a default binding in RoboGuice, your custom Application class has not. So the context will automagically work... – Jeroen Oct 11 '13 at 02:23