dependency injection - Where Do I Declare Unity Container? -
i'm getting started unity, , i'm having trouble finding advice declare unitycontainer object. of examples i've seen consist of single method unitycontainer object declared @ top, mappings defined, few object types resolved. how handle container when need access in several places throughout program? example, user clicks on button opens new window , window needs controller, needs resolve several services? want of services unity manages singletons, wouldn't mean i'd have have single instance of unitycontainer throughout program manage singletons?
my first thought have main program class have static unitycontainer property or expose sort of unitycontainerfactory class manages singleton unitycontainer instance, both of methods seem bad because create global property lot of things dependent on.
what's accepted way of doing this?
as noted in other answer, should compose entire object graph in composition root.
don't declare container static field since encourage developers use service locator is anti-pattern.
how solve problem?
use dependency injection.
here example special winforms case:
in program.main method, create container, register service (the dependency need use other window) , resolve main form , run this:
unitycontainer container = new unitycontainer(); container.registertype<iservice, service>(); application.enablevisualstyles(); application.setcompatibletextrenderingdefault(false); application.run(container.resolve<mainform>());
in mainform, declare dependency on func<secondform>
secondform
form need create main form when button clicked. consider following code inside main form file:
public partial class mainform : form { private readonly func<secondform> m_secondformfactory; public mainform(func<secondform> second_form_factory) { m_secondformfactory = second_form_factory; initializecomponent(); } private void button1_click(object sender, eventargs e) { secondform second_form = m_secondformfactory(); second_form.show(); } }
please note func<secondform>
acts kind of factory. use in case because unity has feature support late construction of dependencies via func
.
the secondform
has dependency on iservice
this:
public partial class secondform : form { private readonly iservice m_service; public secondform(iservice service) { m_service = sevice; initializecomponent(); } //use service here }
you can use iservice
second form.
Comments
Post a Comment