I recently learned about the DI frameworks Guice and Ninject and wanted to use them in some of my new projects.
While I am familiar with general dependency injection concepts and know how to use those frameworks to construct object graphs, I struggle to apply IoC when it comes to dynamic application behavior.
Consider this example:
- When the application starts, the main window will be shown.
- When the user clicks the main panel, a context menu opens.
- Depending on the user' selection, a new user control will be created and shown at the mouse position.
- Should the user eventually decide to close the application, a confirmation box will be shown and - upon confirmation - the main window will be closed.
While it is easy to wire the main window's View to a Presenter/ViewModel and then bind that to the domain logic, I don't understand how to cleanly (in the sense of IoC) achieve the following tasks:
- Dynamically instantiate a concrete UI control (e.g.
IGreenBoxView
,IRedImageView
<--JConcreteGreenBoxView
,JConcreteRedImageView
) without using any kind of service locator pattern (e.g. requesting from the IoC again)- Depending on that, create a new model, presenter and view instance
- Similary, instanciate a new concrete dialog box, e.g.
JOptionPane
at runtime
I've seen some solutions using abstract factories but honestly didn't fully understand them. It seems that such a solution would lead to exposing some of the (view domain's, presenter domain's, ...) internal types to the construction root and, with that, to the whole world.
So - how do I do it right?