views:

216

answers:

2

Say I have a ClassWithManyDependencies. I want to write a Guice Provider for this class, in order to create a fresh instance of the class several times in my program (another class will depend on this Provider and use it at several points to create new instances).

One way to achieve this is by having the Provider depend on all the dependencies of ClassWithManyDependencies. This is quite ugly.

Is there a better way to achieve this?

Note - I certainly don't want the Provider to depend on the injector. Another option I considered is having ClassWithManyDependencies and ClassWithManyDependenciesProvider extend the same base class, but it's butt ugly.

+4  A: 

As mentioned on the mailing list, anywhere you can inject ClassWithManyDependencies you can simply inject Provider<ClassWithManyDependencies> instead, no need to write anything special yourself. Guice does this for you.

ColinD
+1: In summary: @Inject Provider<ClassWithManyDependencies> provider; ... provider.get().doStuff()
Mark Renouf
Also check out the annotations @ProvidedBy and @Provides for a ways of setting up custom providers with less boilerplate.
Mark Renouf
Thanks, I knew I was doing something wrong when I was implementing the providers :)
ripper234
A: 

You shouldn't have to write a provider except to integrate with other frameworks.

Just DON'T bind your ClassWithManyDependencies in scope SINGLETON and in the class that wants to build many instances, instead of having a ClassWithManyDependencies instance injected you have a Provider injected. (Guice can do that for free for every binded class)

On this provider you can just call get(), if not in scope SINGLETON it makes a fresh new instance each time.

Now if you are in the tricky case that ClassWithManyDependencies relies both on some GUICE IOC and on some constructor parameters, then you shall go for Assisted Injections

christian
I disagree. Part of what guice lets you do is strictly split object creation from its business logic. That means that the constructor of an object should do nothing else but assignments. Therefore, where do you put other initialization code? It goes in the provider.
nes1983