Question

I'm trying to override a couple of injections for testing with a specific test module. This works fine as is for real singletons like so:

...custom module...
bind(SomeClass.class).toInstance(instanceOfMockedClass);
...

Now this imposes problems when ContextSingletons need to be overwritten. Doing the same like above obviously injects the same instance for all contexts (services, activities), where a separate instance would have been correct. I tried to wrap my head around the ContextScopedProvider but couldn't find a way to actually use this in a bind(...).toProvider(...) construct, as this class itself does not implement Guice's Provider<T> interface.

How can this be achieved?

(also asked on https://groups.google.com/forum/?fromgroups=#!topic/roboguice/MnWGrHFDOsQ)

Was it helpful?

Solution

An alternate way to write that for a regular singleton would be something like this

bind(SomeClass.class).toProvider(SomeClassProvider.class).in(Singleton.class);

If you do it that way, you don't need to have the instance available at the time of the binding, which while fine for a Singleton, obviously won't work for a ContextSingleton since there's no context yet.

You can use the same kind of binding for a ContextSingleton:

bind(SomeClass.class).toProvider(SomeClassProvider.class).in(ContextSingleton.class);

Now, all the instances of SomeClass that RoboGuice injects for you will be properly scoped, whether Singleton or ContextSingleton.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top