I’m currently experimenting with the Google’s guice inversion of control container. I previously had singletons for just about any service (database, active directory) my application used. Now I refactored the code: all the dependencies are given as parameters to constructors. So far, so good. Now the hardest part is with the graphical user interface. I face this problem: I have a table (JTable) of products wrapped in an ProductFrame. I give the dependencies as parameters (EditProductDialog).
@Inject
public ProductFrame(EditProductDialog editProductDialog) {
// ...
}
// ...
@Inject
public EditProductDialog(DBProductController productController, Product product) {
// ...
}
The problem is that guice can’t know what Product I have selected in the table, so it can’t know what to inject in the EditProductDialog.
Dependency Injection is pretty viral (if I modify one class to use dependency injection I also need to modify all the other classes it interacts with) so my question is should I directly instantiate EditProductDialog? But then I would have to pass manually the DBProductController to the EditProductDialog and I will also need to pass it to the ProductFrame and all this boils down to not using dependency injection at all.
Or is my design flawed and because of that I can’t really adapt the project to dependecy injection?
Give me some examples of how you used dependency injection with the graphical user interface.
All the examples found on the Internet are really simple examples where you use some services (mostly databases) with dependency injection.
From what I see in your sample code, I am not sure passing
ProducttoEditProductDialogis the best design, this means that you cannot reuse the same dialog for 2 different products.In general, I would rather add a
setProduct(Product)toEditProductDialogin order to:Besides, you can also, if you want to keep the current constructor arguments, take a look at Guice Assisted Injection, which would allow you to have all dependencies injected into the constructor, while still providing the product explicitly.
Finally, you may want to take a look at Guts-GUI, an open source framework for creating Swing GUIs with Guice (still under work, but ready to use as of today). It has a sample application that contains examples of reusable dialogs.