I am new to Guice, and to DI libraries (I've never used Spring, etc.), although I've used similar patterns myself (always take dependencies in ctor; try to restrict new to "factories"). I'm trying to see how I can use Guice on a totally new project, but I'm trying to understand lifecycles.

As an example application to learn, I wanted to use some JDBC via a SQL DataSource object; I figured Guice to inject this is a great idea. I implemented a @Provides method in my module to actually initialize the DataSource and return it (I hope that is OK), and I marked it as Singleton to restrict to one DataSource per injector (application).

But, how do I shutdown that DataSource, or any other resource that I acquire? Right now my application is Guice.createInjector.getInstance(TheMainClass).go() and then after that (go returns after the app is done), I do getInstance for the DataSource to call close on it. That really doesn't seem right to me; what if no one ever asked for the DataSource?

I realize that there are pooling data sources that can timeout idle connections, and you can make a resource in which close does nothing if no one ever opened/used it. But what if the resource doesn't work that way? What method does one use to say the module is "done"? Or is the way I did it the best way?

This problem comes more apparent if I have a Guice app that wants to do a task; let's say a button "backup DB to FTP" that might never be used. But if it does I want a bunch of "session" state that is "singleton" to that case, and then all cleaned up at the end? How do I do that? Scopes? Child injectors? I thought Scopes would be it but don't seem to make sense; the SessionScope/RequestScope I learned rely on "global" state, and I'm not in a servlet anyway.

Thanks,

Jason

--
You received this message because you are subscribed to the Google Groups 
"google-guice" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/google-guice?hl=en.

Reply via email to