title: Multiple implementations in Guice with indirect dependency
body: <p>My Java code uses multiple implementations of an interface (BugTemplate in the example below), where the bound implementation depends on context.</p>
  
  <p>In Guice, I believe the proper way to accomplish this is with BindingAnnotations. However, my use case is different than the canonical example, in that the context is one level removed from the interface's implementation.</p>
  
  <p>Summarizing the possible dependencies:</p>
  
  <blockquote>
    <p>FooBugFinder -> BugFiler -> FooBugTemplate</p>
    
    <p>BarBugFinder -> BugFiler -> BarBugTemplate</p>
    
    <p>etc.</p>
  </blockquote>
  
  <p>Example code:</p>
  
  <pre><code>class FooBugFinder {
    // ...
    public findBugsAndFileThem() {
      List&lt;Bug&gt; bugs = findBugs();
      bugFiler.fileBugs(bugs);
    }
    @Inject
    FooBugFinder(BugFiler bugFiler) {
      // BugFiler should have been instantiated with a FooBugTemplate.
      this.bugFiler = bugFiler;
    }
  }
  
  class BugFiler {
    // ...
    public fileBugs(List&lt;Bug&gt; bugs) {
      List&lt;FormattedBugReport&gt; bugReports = bugTemplate.formatBugs(bugs);
      fileBugReports(bugReports);
    }
    @Inject
    BugFiler(BugTemplate bugTemplate) {
      // The specific implementation of BugTemplate is context-dependent.
      this.bugTemplate = bugTemplate;
    }
  }
  
  interface BugTemplate {
    List&lt;FormattedBugReport&gt; formatBugs(List&lt;Bug&gt; bugs);
  }
  
  class FooBugTemplate implements BugTemplate {
    @Overrides
    List&lt;FormattedBugReport&gt; formatBugs(List&lt;Bug&gt; bugs) {
      // ...
    }
  }
  </code></pre>
  
  <p>My first thought is to annotate the ctor as follows:</p>
  
  <pre><code>FooBugFinder(@Foo BugFiler bugFiler) { }
  </code></pre>
  
  <p>However, how would Guice know to apply that annotation when injecting arguments to BugFiler's constructor?</p>
  
  <p>In other words, FooBugFinder needs a BugFiler instance which was instantiated with FooBugTemplate.
  BarBugFinder needs a BugFiler instance which was instantiated with BarBugTemplate.</p>
  
  <p>Any ideas?</p>