Note that there are some explanatory texts on larger screens.

plurals
  1. POProper structure for dependency injection (using Guice)
    primarykey
    data
    text
    <p>I would like some suggestions and feedback on the best way to structure dependency injection for a system with the structure described below. I'm using Guice and thus would prefer solutions centered around it's annotation-based declarations, not XML-heavy Spring-style configuration.</p> <p>Consider a set of similar objects, <code>Ball, Box, and Tube</code>, each dependent on a <code>Logger</code>, supplied via the constructor. (This might not be important, but all four classes happen to be singletons --- of the application, not Gang-of-Four, variety.)</p> <p>A <code>ToyChest</code> class is responsible for creating and managing the three shape objects. <code>ToyChest</code> itself is not dependent on <code>Logger</code>, aside from creating the shape objects which are.</p> <p>The <code>ToyChest</code> class is instantiated as an application singleton in a <code>Main</code> class.</p> <p>I'm confused about the best way to construct the shapes in <code>ToyChest</code>. I either (1) need access to a Guice <code>Injector</code> instance already attached to a <code>Module</code> binding <code>Logger</code> to an implementation or (2) need to create a new <code>Injector</code> attached to the right <code>Module</code>.</p> <p>(1) is accomplished by adding an <code>@Inject Injector injector</code>field to <code>ToyChest</code>, but this feels weird because <code>ToyChest</code> doesn't actually have any direct dependencies --- only those of the children it instantiates.</p> <p>For (2), I'm not sure how to pass in the appropriate <code>Module</code>. </p> <p>Am I on the right track? Is there a better way to structure this?</p> <p>The answers to this <a href="https://stackoverflow.com/questions/2176216/how-to-inject-injector">question</a> mention passing in a <code>Provider</code> instead of using the Injector directly, but I'm not sure how that is supposed to work.</p> <p>EDIT:</p> <p>Perhaps a more simple question is: when using Guice, where is the proper place to construct the shapes objects? <code>ToyChest</code> will do some configuration with them, but I suppose they could be constructed elsewhere. <code>ToyChest</code> (as the container managing them), and not <code>Main</code>, just seems to me like the appropriate place to construct them.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload