Reputation: 4666
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?
Upvotes: 2
Views: 568
Reputation: 18397
If you want Guice to inject your objects for you, your objects are going to be coupled to Guice. That's the way Guice works. You could get around using the Provider interface by creating your own Factory interface and injecting that, but you'll still have to have an @Inject somewhere which will couple you to Guice.
Personally I think you should reconsider your requirement of having 0 coupling to Guice, but if you absolutely have to be able to write classes that have no references to your DI container, you should look at something like Spring.
Upvotes: 1
Reputation: 110046
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 the Injector
all over the place) it's fairly easy to, say, change all places you injected Provider
to 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.
Upvotes: 3