I created a class that uses the the Java Executor API to create/manage a pool with fixed number of threads.
Each thread needs a new instance of a particular object, and I would like to inject this object with Guice.
For the moment I’m using a Provider which provides new instances of the object through its get() method.
But now this class has a dependency to the Provider, which is Guice specific, effectively coupling the code to the Guice framework.
I would really like the class to be truly Guice agnostic, is this possible?
Just creating new instances of using the ‘new’ keyword is not an option, as this makes it impossible to replace those object by a mock implementation in the unit test.
Dependency injection is probably not suited for this and I would be better of creating a factory to get these objects?
One thing you may want to consider is building Guice from trunk and using that until Guice 3.0 is released. Then you can use JSR-330‘s javax.inject.Provider instead of Guice’s.
Edit: Other than that, I’m generally of the opinion that coupling to the DI container (by importing something from
com.google.inject, in this case) is less of an issue than people sometimes make it out to be. As long as you aren’t depending on the details of how you get your dependencies (e.g. injecting theInjectorall over the place) it’s fairly easy to, say, change all places you injectedProviderto take your own interface with a similar function instead. Depending on powerful features like scoping is where you really couple yourself to the container. I think that’s fine as well though, given how much ugliness and effort they save you.