c# - Doing dependency injection right in a WinForms application with subforms -


let's main form have few menu items. each menu item show form. following code way dependency injection in scenario?

public class mainform: form {   private iaboutform _aboutform;   private ioptionsform _optionsform;   private idownloadsform _downloadsform;    mainform(iaboutform aboutform, ioptionsform optionsform, idownloadsform downloadsform) { // add many form dependencies required     _aboutform = aboutform;     _optionsform = optionsform;     _downloadsform = downloadsform;      initializecomponent();   }    private void aboutmenuitem_click(object sender, system.eventargs e) {     _aboutform.showdialog(this);   }    private void downloadsmenuitem_click(object sender, system.eventargs e) {     _downloads.show();     _downloads.bringtofront();   }  } 

this works fine as-is, doesn't extend - constructor become huge after while if continue add forms. if never add more, fine. if know add more, or don't think end doing so, may want inject iformfactory of sort instead, so:

iformsfactory formsfactory; mainform(iformsfactory formsfactory) {     _formsfactory = formsfactory; } 

then can create dependent forms needed:

private void aboutmenuitem_click(object sender, system.eventargs e) {     iaboutform aboutform = _formsfactory.createaboutform();     aboutform.showdialog(this); } 

there's several ways can go this. can keep forms member variables, , use injected factory create them in constructor. if performance concern, , need single instance each life of program.

note can add "construction" parameters factory.createxxx() call if needed too.

inside factory, know how create each form. if use ioc container, don't need create concrete of ifactory interface. if there's special logic creating form though, may want create concrete instead , resolve injected ifactory concrete.

there's quite bit more can said this, starting point think. hope helps.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -