开发者

How do I write a Guice Provider that doesn't explicitly create objects?

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 ti开发者_高级运维mes 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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜