1

Unless a singleton object in graph is annotated with a Qualifier we can just call:

graph.get(Bus.class);

If this object is annotated in the module definition with a Qualifier then it will throw IllegalStateException.

Is there a better way of retrieving that object from the graph than:

public class BusWrapper {
    @Inject
    @MyQualifier
    Bus bus;
}

and

graph.inject(new BusWrapper()).bus;

I have a set of graphs (one graph for each account). Separate bus for each account graph and one app scoped bus (annotated with different Qualifier). Once I receive a GCM sync request message I need to retrieve the bus from the correct graph to pass the sync request.

gswierczynski
  • 3,813
  • 2
  • 21
  • 22
  • Think I would create and provide a BusFactory and associate a id/name for each Bus. Then when GCM arrives, do something like `busFactory.getBusByName('nameOfBus').` – cYrixmorten Oct 05 '14 at 16:11
  • @cYrixmorten That isn't at all safe or statically analyzable, all both of which Dagger and qualified injections provide. – Jake Wharton Oct 05 '14 at 17:38
  • What object is this code inside of that it can't just inject the all of the qualified `Bus` instances directly and then switch/ifelse between them? – Jake Wharton Oct 05 '14 at 17:40
  • @JakeWharton Do you mean the the BusWrapper should have a member for each of the types of the Bus? I get it - it will work. The place where I need that is out of Account scope (there is one service for all incoming messages). It actually looks like application.getMapOfAccountGraphs.get(account).inject(new BusWrapper()).bus.post(Event). A the moment I only need one type of bus and the code above is doing what I want. I was just wondering if there was a way to retrieve specific type of Bus with get() method and/or the snippet above is OK. Thank you. – gswierczynski Oct 05 '14 at 18:53

1 Answers1

4

Performing annotated instance lookups via .get() is not supported.

I couldn't find a good reference post to cite. The closest is this one:

Dagger 1.0 is definitely designed around having robust entry-point/injectable objects, rather than using ObjectGraph like a big annotated map.

Basically, .get() was designed to be used for grabbing the root instance from your object graph under which all dependencies would be @Injected normally.

Jake Wharton
  • 75,598
  • 23
  • 223
  • 230