Note that there are some explanatory texts on larger screens.

plurals
  1. POSingleton Provider vs Regular Provider
    primarykey
    data
    text
    <p>I'm attempting (for the first time) to build up a token using dependency injection. I have a diamond hierarchy problem, where I need to prepend a signed hash of my data to the actual data itself. </p> <p>As a result, I find myself calling get() on the original data provider multiple times. This would be fine, but further down the graph, there are time-based components and as a result, the data returned on subsequent calls is different.</p> <p>A solution was suggested to use the Singleton Provider model. For this Provider, subsequent calls to get() return the same object (reference). This Provider caches the result of the first call to get() and continually returns that. When injecting dependencies, I inject the same instance of this provider twice, and as a result it returns the same data twice.</p> <p>This got me thinking, is there any situation where you wouldn't want to use a Singleton Provider? If you expect a different result, shouldn't a new Provider instance be created every time?</p> <pre><code>public MyUnderscoreStringSingletonProvider implements Provider&lt;String&gt; { private final Provider&lt;String&gt; mySomeOtherStringProvider; private String myCachedString; public MyUnderscoreStringSingletonProvider( Provider&lt;String&gt; someOtherStringProvider ) { mySomeOtherStringProvider = someOtherStringProvider; myCachedString = null; } @Override public String get() { if( myCachedString == null ) { myCachedString = create(); } return myCachedString; } private String create() { return "_" + mySomeOtherStringProvider.get(); } } // ... public class SomeCoolService { // ... public Provider&lt;String&gt; injectStringDoubler() { final Provider&lt;String&gt; stringProvider = injectUnderScoreStringProvider(); return new TwoConcatendatedStringsProvider( stringProvider, stringProvider ); // This would not work if Singleton Provider was not used. // Why should we ever use non-Singleton Providers? } protected Provider&lt;String&gt; injectUnderScoreStringProvider() { return new MyUnderscoreStringSingletonProvider( injectMyTimebasedStringProvider() // returns different result // depending // on time. ); } // ... } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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