Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Depending on what you mean by your question, here's what Guice (a DI framework for Java) uses:</p> <p>If you simply want a distinct object every time you have an injection request for <code>Foo</code>, then when wiring up your application don't bind <code>Foo.class</code> to a particular instance of <code>Foo</code>, but instead bind a <code>Provider&lt;Foo&gt;</code>, which is an object that creates a <code>Foo</code> on demand. Then, every place where <code>Foo</code> is injected will get a new instance. If you just bind <code>Foo</code> to a class instead of a <code>Foo</code> instance (say, <code>Foo</code> is an interface, and you bound it to <code>RealFoo.class</code> which is a class that implements <code>Foo</code>), you also get the same effect - a new instance is created every time. (This is the default, "unscoped" behavior. The behavior of Guice scopes is beyond the scope of this comment)</p> <p>If however you need to have two instances of <code>Foo</code> that you construct when wiring up your application and then have the ability to say "This instance of Foo gets used when making a <code>Bar</code> or a <code>Baz</code>, whereas this other instance is used when making a <code>Bumble</code>", what you do is annotate the injection points and then when wiring up your app say something like:</p> <pre><code>Foo foo1 = new Foo("1"); Foo foo2 = new Foo("2"); bind(Foo.class).annotatedWith(Names.named("Bar")).toInstance(foo1); bind(Foo.class).annotatedWith(Names.named("Baz")).toInstance(foo1); bind(Foo.class).annotatedWith(Names.named("Bumble")).toInstance(foo2); </code></pre> <p>Where I assume that you've annotated the arguments to <code>Bar</code>'s constructor with something like:</p> <pre><code>public Bar(@Named("Bar") Foo foo) { ... </code></pre> <p>And similarly for <code>Baz</code> and <code>Bumble</code>. Of course, if you annotate the constructor of <code>Bar</code> and <code>Baz</code> with the same thing, you can skip one of the <code>bind</code> lines.</p> <p>I know there are annotation-processing frameworks for php based on reflection, or perhaps you can use a convention based on argument names.</p>
 

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