c# - IoC / DI containers, factories and runtime type creation -


i learned di frameworks guice , ninject , wanted use them in of new projects.

while familiar general dependency injection concepts , know how use frameworks construct object graphs, struggle apply ioc when comes dynamic application behavior.

consider example:

  • when application starts, main window shown.
  • when user clicks main panel, context menu opens.
  • depending on user' selection, new user control created , shown @ mouse position.
  • should user decide close application, confirmation box shown , - upon confirmation - main window closed.

while easy wire main window's view presenter/viewmodel , bind domain logic, don't understand how cleanly (in sense of ioc) achieve following tasks:

  • dynamically instantiate concrete ui control (e.g. igreenboxview, iredimageview <-- jconcretegreenboxview, jconcreteredimageview) without using kind of service locator pattern (e.g. requesting ioc again)
    • depending on that, create new model, presenter , view instance
  • similary, instanciate new concrete dialog box, e.g. joptionpane @ runtime

i've seen solutions using abstract factories didn't understand them. seems such solution lead exposing of (view domain's, presenter domain's, ...) internal types construction root and, that, whole world.

so - how do right?

if can reuse controls can constructor injection use them. otherwise have inject factory:

public interface icontrolfactory  {      igreenboxview creategreenboxview();      iredimageview createredimageview(); } 

and inject need create controls.

the implementation goes container configuration. there can inject container implementation. containers provide implement factory automatically. e.g., in ninject:

bind<icontrolfactory>().tofactory(); 

see https://github.com/ninject/ninject.extensions.factory/wiki


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -