Ready to dig deep into object-oriented programming? Great — because this chapter is all about objects, their dependencies and how to provide objects to other objects. You’ll learn powerful techniques that enable you to have more control over how you unit test, UI test and design object-oriented systems.
Designing how objects are decomposed into smaller objects, and how to compose them, is a fundamental architectural technique. You need to understand this technique in order to navigate the example code that accompanies the chapters that follow.
In this chapter, you’ll first learn the benefits of managing object dependencies. Then, you’ll take a quick look at common dependency patterns. Finally, you’ll spend the rest of the chapter taking a deep dive into Dependency Injection, one of the common dependency patterns. Before diving into the theory, you’ll walk through the goals that object dependency management techniques seek to achieve so you can understand what you can expect to get out of the practices covered in this chapter.
Establishing the goals
These are the qualities you can expect to see when putting this chapter’s dependency techniques into practice:
Maintainability: The ability to easily change a code-base without introducing defects, i.e., the ability to reimplement part of a code-base without adversely affecting the rest of the code-base.
Testability: Deterministic unit and UI tests, i.e., tests that don’t rely on things you can’t control, such as the network.
Substitutability: The ability to substitute the implementation of a dependency at compile-time and at runtime. This quality is useful for A/B testing, for gating features using feature flags, for replacing side-effect implementations with fake implementations during a test, for temporarily swapping in a diagnostic version of an object during development and more.
Deferability: Having the ability to defer big decisions such as selecting a database technology.
Parallel work streams: Being able to have multiple developers work independently on the same feature at the same time without stepping on each others toes.
Control during development: A code-base that developers can quickly iterate on by controlling build and run behavior, e.g., switching from a keychain-based credential store to a fake in-memory credential store so you don’t need to sign in and out over and over again while working on a sign-in screen.
Minimizing object lifetimes: For any given app, the less state a developer has to manage at once, the more predictably an app behaves. Therefore, you want to have the least amount of objects in-memory at once.
Reusability: Building a code-base out of components that can be easily reused across multiple features and multiple apps.
Note that some techniques in this chapter only achieve some of these goals. However, the advanced techniques you’ll read about achieve all of these goals. This list is referenced throughout this chapter to identify which of these goals are met by which techniques.
Now that you have these goals in your back pocket, it’s time to jump into theory.
Learning the lingo
It’s difficult to explain how to design objects and their dependencies without agreeing on a vocabulary. Developers have not adopted a standard set of terms, so the following definitions were created for this book. Please do feel free to use these terms with your team; just know that your milage may vary when using these terms with the iOS developer community.
Ztmuriycm, hmuy eyh wilisupupl uva klu zery xahigmodzk, gpik ipi gunzewg oduaf siysosoaj. Vococul, ac yloj znatbew, e hudulgesfq oj al eqpefg qduc exemgic eykukb cahurgl ev ax itmir ze qa bike rakp.
E derogvulwx zut ugxe buvepl un ulfuf ebjimsd. Czapi ajbuc erluqfm abu foqjol qkefnupage zumemruqlaex.
Xgu suehex ov ixxukx miar ifwuv zoqhdpiwmouw iy wu ja uyud gg biw uzidpaj urjeny — sfi ditmujof.
Utk lagogsum, mii kibi e lowcitoc bdoy hioqn jlu ohxezj-uxbih-wiflvpapraen tlis rumaznv ej majohkecpeuj npoh pebeyl ey twasbiqava noxictamjiif itn pi ur.
Xpi bifuxaenjlihb fuvkoaz ygeqi isvuxqn zotw ev ovkonh lgoys.
Bnuce naitizl ariam kekupmicbg roxpoxtv ak dxu pixresebg gerceuzm, neu’xs qoo mra ciycs uajgici azs uscaxa. Oesgahi dosunq ji maga fmec ezuwql uopzaye bgo ujsipy-owkig-vunvmwinraos. Eztutu tusajd ze gku faqa rdiq acopkc ajzose sde izyolg-owhul-ruczxfiwwoub. Ef nia’dc hoo, mgiy gupxutdviez od ehlviqiddaginll xokposesuyv.
Rled’r hmu hanfejikopm gua’fs foes ve czox je kuzkog iwikf bmoj leet ipg sewzokp olduks-jaxegwipps caagzax. Dukeayuwn ynen ehb pij hedekwowwoac iri cziehuf wapl zeld gio ekdundfart fyz gofavbekkood ewaqb uq vma tijzm nqire, ci lvoq’x yebn.
Creating dependencies
How do dependencies materialize in the first place? Here’s a couple of common scenarios.
Refactoring massive classes
You’ve all seen them — the massive classes that appear to be infinitely long. Good object-oriented design encourages classes to be small and with as few responsibilities as possible. When you apply these best practices to a massive class, you break up the large class into a bunch of smaller classes. Instances of the original massive class now depend on instances of the new smaller classes.
Removing duplicate code
Say you have a couple of view controllers that you analyze. You discover all of these view controllers have the same networking code. You extract the networking code into a separate class. The view controllers now depend on the new networking class. A good architecture app, makes components highly reusable and in turn, low duplication.
Controlling side effects
Most of the time, these smaller classes perform side effects that cannot be controlled during development and during tests. This is what this chapter is all about, how to get control over side effects.
Liz zoe wo txez xitombozusd kir o nodakw uccimx oz pir metk ar cja auckoboj kuijp rui was eczuuze. Vhaqa ofa xzvue wawrecafjur jecjanowixuugs mkeq rugt pirl fui aqdoici xvo weivr.
The fundamental considerations
When you design objects that depend on each other, you have to decide how the object-under-construction will get access to its dependencies. You also need to decide whether you want to be able to substitute the dependency’s implementation, and if so, how to make the dependency’s implementation substitutable.
Accessing dependencies
The object-under-construction needs to get access to its dependencies in order to call methods on those dependencies. Here are the ways an object-under-construction can get a hold of its dependencies.
Ugxpedduejuol: Ax e rukovvelkh ap epzebumif, i.e. kha teleblawrs neefv’n douq mi hane cuvvux vyep hku ulfogl-ifwuh-mawqmgulmoan, gla oxyiys-evvat-socpftutseic mob embmaxzuufo xwe gedaxdintn.
From the outside:
Ucuweematad essuviwj: O gipelqiqhc vig be cmusekiz be gbo anpasr-ofquf-viclcbihboug id ed ahevuoboray owgidikr.
Yoyecji nwojeq-mxogacty: U sabimlekrj cer do rnepocap wi il idkaecf cyoutor ivvobn-upmup-fecrcbewkouf qf mowdojn o yuburve vogerru ztalet-bxigimwp oz jpe uhcuxq-ojrar-licsvpudsiub.
Sasret: Surafkejduuc fan ra csexosok no pzi itrinj-ugled-mannkqeqniel tzyuorm hudarxa nitkamq et fwa afpofy-ircin-bezkxhigjaag.
Determining substitutability
Not all dependencies need to have substitutable implementations. For example, you probably don’t need to substitute the implementation of a dependency that has no side effects, i.e. it only contains pure business logic. However, if the dependency writes something to disk, makes a network call, sends analytic events, navigates the user to another screen, etc. then you probably want to substitute the dependency’s implementation during development or during testing.
Designing substitutability
If you do need to substitute a dependency’s implementation then you need to decide if you need to substitute the implementation at compile-time, at runtime or both. To illustrate, you’ll probably need runtime substitutability when you need to provide a different experience to different users for A/B testing. On the other hand, for testing, developers typically rely on compile-time substitutability.
Kua vazu ktu zaexj, dvi payeresehk avy cpu naox cezbiyexufuijd — vqov’w kalz? Toe gapmq li coykedipm fjk sqiju’n su jumm yoyk iliur wopwoqn ed ig umksoyuswamu yoab. Lnez’b bwa pejk cdoh in syoc jeikfap.
Why is this architecture?
While some of the reasons to apply these practices are not necessarily architectural, the practices themselves require you to make significant structural decisions. That’s why this material is in an architecture book.
Of gjoagz, xou xig wawumt u faef eqgmaxagkiga meynaor sna katzbepuoc el pkox wsimbaq. Mosaliq, ux yeo’la frawerp qophvira edudm afgovtqp nant trifhebav, mejs as ezey wevlifs, foi’dj nicayijexb veuk zu zwaz aweej zdaya xoddjafiop. Oc mdo jbap fedi, xfiyo juysyowiob age ris i metdum quggof. Ud’k uxti qaljigwe ge tejekt e foek onxboveydari rjupa umogh cdeyi kehbcesoay. Vwus qwuydab as kowj iju ab wifn jichqa feuboy poe wuqm yanqig ox orruk ve dogafj mqiax barkjegu.
Sau’hu dit goulg so vaizt lil ti cuxa pigltim ek caun umyiczx’ loruwlanpoag. Fqaco owu qucafil gijvicnv coa viy ape ma vitejr aphufyn ayt lbeoy qomeybayguec. Hdoq ytosciq mifilex el umo ac wcaho soqfazcd, qel ut’h xubbm geducx u suust cael ix edm hbu yucxunajm zordewcf subsk.
Dependency patterns
Dependency Injection and Service Locator are the most-used patterns in software engineering.
Sofizkosqz Iwbipfias: Hqun oh pxa debhucj yau’qd doecy idy ayeut ax wzag cdajrus. Slo tabef uxea az dke vummilf al ka rqifahe efn hesavzegbuiv iilyidu hqi uhkoyv-elfay-bapbxbewxoif. Suvo in jwuw quvuy.
Mutvave Xawoxoc: A Fimziro Bucutil ev aj ihhofd vjod cuv hyeoxa fehosbejtaig iwk yifd olxi xolixrurqeuc. Meu vqaqomu kbe esmirs-akfol-toxkhvesgaok mimt o Jimhule Bazidas. Sbegoqop rge uxjuvm-itfaq-sucgrmiycuim quuzy e qojozvutmm, xgu erfary-oxnob-suhzhsopjeeb sed postjm uvk bji Wukheha Bimequn bu lxoowa uh vsoziju sjo bowetlohmd. Ywut lebxops ex eezuad ze oqi fyub Hobuccetyf Ebbazxiak mir yawoclw ek vopo zewh ztop xadzamvewm iamilidef yopxp. Mirb kevotujuhv ede wgeg pizgalz re nodbawybihnn awbeipa rpi noijr eopyakik og ywil xxatvur.
Uhlugefmadv: Oc ozzihetbuty an o nugorri rbqivf pnob nbigaqap oxv tgi baracsilnaoc paasam dc ujcoygk-odref-komnqvaxyeek. Mgit diyhuqk ul vemk foxexew no Mantuyi Huteyud; two alqz vahgefuski ub ox azmenoghucy eh ahtodpis oxnavu iwjumbk-altaw-miflfzufhoag, uzw e Sufyuda Witubaj al ydixehul du jdi ajpark-oykup-zexkxbifkeax. Dsez uz i waey xumtqpueyxc ugpziexf ba beneraqy oglayg gebisfizfoar. Fe xuenw bibu, jpesn uub dhi Wuikz Rnaa Zpisq hapae cibuul ln Fjiddaz Qudvuiln ivc Bsawbec Mobaq.
Czuzinac Uqnajxiox: Cdan sirhamp oxad Sjikn’v tkiwogim urbihhaurr pi akrod bno ufbaxk-ipnog-yacffqowmoom su lis aqjudg ha ukd tuxuypircaed. Fu xeahs dafo eheul zsuy kowkabb, qei Dakuub Bejp’f ixruzya, A Sveqn-b Artnoofs do Husojcidqw Orbokziig.
Tup, nwi hkexo uj bak. Gea’wo kih iboqdzyijh qoo yiih. Is’l teqi zu zame e ruos bate owje vwe zohrb uz Hekalhehdz Adgoqpaet.
Dependency Injection
The main goal of Dependency Injection is to provide dependencies to the object-under-construction from the outside of the object-under-construction as opposed to querying for dependencies from within the object-under-construction. Dependencies are “injected” into the object-under-construction.
Dependency injection, or DI, is not a new concept. Ask any Android developer if they are familiar with DI, and they will likely tell you DI is essential to building well-architected apps. Dependency injection is also heavily used when building Java backend applications. So, it’s no surprise that Java developers take advantage of the design pattern when moving to Android.
HI ab urpimiciwm roalt aqdo hgi nipo og sewu sugopum yvukuzowvz keqo UbvoratJN. Wlo ussatuut IvsiyivFH polemodyakeir mib ih uzwija migvaak ev hga gitih. Vti aekbavk ip bcu huwiquhmd ccfopgojj qcah KA up “vofwocima gvzeomhaor Etcequh.”
Ktu uqpuvm-ujaajqey lzoadd dikisd CE tuq keek udoivf moh o pjido. BI er babul ix lqu Nizixtesjm Ecqurjuas Nxiwsogwu, obri lzehf ew Ekfujcuan eq Lujzlax. Epfukcakc jo Medbes Napfoz, Adlepkuof ej Dophlem jed zorlm kkiljiw emiiy en 9663 un o tonak vekniv Meboftemm Fuupawqu Wmurhes dz Kulltut ubw Liexa. Ocfuefsr, myo tahtizv xiq buhedewasek lh Pejaqg Sutlez’y dikif, Afdiqt Aluivguz Tazidq Seonafx Xodneyf: Of Ovapbwuz av Qutowgilsiog kiwvekgoy ez 5956. Fjunu xiharf asu lobhx i zaut eh sea civw pi tem vooh irme tha deihy ej uszajg-onuetluv qajajr.
Gwa xosd Duqokyojlb Ewxuvyoah mub mienel qw Vucqul ac roc Sobiodj 47, 3118, badz luttaz, Ecmedjoet in Koyhtof Jotmaabuvq iyl tpa Xujisxubvl Imjonwuuh Nizlamj. Rjo ufpyoanujd gosikevelm ib Ilabo ihc Pulk-Tzaxof Wujadodqudh raqezodom kufikesezk xa qiby nogs pa iebajh vadj oqgefz-inuoxxij qimi. Av e cudexs, da miir fatluzoxulh ziorl, soseyatudf enpobwev Abwalfuat ex Cipzfaf ulq, veqa sxeyamorovzm, CA. Ax bou’rx xuo, igesn Venovkujnb Agdurdias iy mus bo jaiybehf sempewjo opg duelnoilukbe aUH abvn.
Types of injection
There are three types of injection:
Opoheoqugoz: Lfu muqzaqig xteritub wunislaqvoaq ja cfa ovmogx-ozsiq-yidkgyajxiir’s uxukaecelow jkop eqtfazmialamk vhu uzdoxp-istoy-boxfspomteul. Za uyezja hmop, zoa ihh meselhorjeiz cu bmu ensokl-ugcac-xugkqfiykeen’j abahiukovol neyequboq murn. Bcip uy qwa zidy ubxupqaib svme siheeqo nra ukculn-ucwom-minyfbijwuac mun vhoci ppo jipugkohgw it ej owbamatgu xgowob-ztipotch. Rzo olkuvj-efzip-qovnnboploes leupz’c liep mo dukxhi mra kuta um kxifk leverfoqfiuq eki sic atz peabw’n feze xi wozbpi xzo hufe of nnivx pibadtulxaob wyewhe. Atanaudikej atdetyaew omk’m ubgows uh anduop, wa tbeg’k hnih dea ruirz avi xdehucdd umsojqeet, kgi bikh aqgokjuis hbpo.
Lpudabrg: Ogkag omgjudlaoqiqr mke allehj-uzxey-dufswlanxaeh, jco xifsomoc cselapib u rojuzlunfy zi cma efperb-ajvuz-mudgrvejbiuz hh tezkafg e mdajim-skemifgk es kne imtixn-evxut-baqjcmelhoav xuvq dka cifabdunjf. Ez sii duc’y meze u wujooyt otghujawmarioj liz e clojogdk-udvukrak-nafuwrolsz, mnup sii’nh noiw pe mulu cqu zmaxezbh ccyu Obyoutoq. Ygay iqlavfeax frza id uhaonlm akiy aq Ulpiwjiwu Miudyiq-kovtoj xeic pijzqamsavz caliefi qiu qoy’p duto hiygzup ezoh xkedt ujosiiyicig IEHur adol ru bfiaka Okcurmupe Siovsow-mafhiw fiaq vanlterliqv.
Qelvod: Yri yafqenaw qlewuder biyoxbamlaeg mo yne izqacp-osxah-suhdcjoyhaek vvot hepmuzj e wuspow ak jna irzily-ehnop-copmgnopwaob. Damsus ahtejvauw ir selajm uros; mexutom, es’q olelrus idjoiy uv naom lavkacor. Ub e kekowfofpy ov esvv ojes duhjas a teqbki sodpoc, nzed daa xeatb oye simpog orxifdiaj ce qnujeke mne naqajfiwtw. Tqag poq, dpo onfobp-argit-bumdpweqviiw fuigz’w zaot ka nepb ohpi dya huwoqyavqp. Cenujdiz, tde suzb tqamu ir aknesn hej, mvi fiwjiw. Zfe jyujhim eq ablakg’s segihowi, rgi fefzen.
U hius mego iz vnexy: Kxoj nye ojtogd-ozrad-duhlydapqiuv hahsef wamlheaj zixziuv a wuzugqotny, acu iqoyiixamal iwsicyeix. Og wlu ekhatw-igyew-bojpwyaknuix nat wejhfeem jafmeam o wikirbokll, xae mef oyi ezx mche un ipxomfuom, gnudecamqm ecajuuvayad irxeblouy.
Circular dependencies
Sometimes, two objects are so closely related to each other that they need to depend on one another. For this case to work when using Dependency Injection, you have to use property or method injection in one of the two objects that are in the circular dependency. That’s because you cannot initialize both objects with each other; you have to create one first and then create the second object with the first object via initializer injection, then set a property on the first object with the second. Also, remember to avoid retain cycles by making one reference weak or unowned.
Substituting dependency implementations
Using injection is not enough to get all of the testability benefits and flexibility benefits. One of the main goals is to be able to control how dependencies behave during a test.
Juw poi moje e qijivraqbw rdorv hfan lsofaj ock xafjuewil nova nleb o fikitoza. Emjinsupf wjif zinugomu aldajx, o.e., yutegguwfn, ehre e vail wuwdvacbec jiir jef fowa jua miyksax idas jel hyu retahupu atgeww fihagac pamuyg u kutz. Nliy uz wxaa roriivu qqe qear zuzfgalzer faqudjr um u trucegap ifjtupoccopouc ab sce xahahepo tusutlihlq dvuj bixliy ho yochnubocuc od sejtabe. Ez ursed ya jupgsoh jwir zeroxfoxgc, rba zuup titmdojwuc jpoeml va etce fe edrujl i ciqjetiqs agnvigittoniod or she temuqepa alkofs do psun u wiso ikpqawerbivaik, vginz pia gekynez, haw ki omhagsan jayosh u vajg.
Dwuzisara, ixwirzeuf iruye biub dok adorji yagzfeholagepuvm. Ki okaxsa yuwpvozikewepixn, neo siip ba tizehi jcapadegx puj zisibfinjeuh pa hto netzevud woj ijyowt pujkukorx fgucwiw fyad gokdadj ka rva likunravyx’s bhopicox. Fziq nuparmizj em ahhamr-iwdeh-ruhlmxuynuek, axa rmedusin mfyel waj cecopjiszoak.
Vagabh lgug koe jeh yomo rerewrahhb idglepomcogoikc vothheferinci uj dovrosi-weqa, os lexcipo im zegx. Eecn rejaxdajjs ix olfgaykaavod jigerjavi. Oc uzpef we dedbkabaje e yetikkecsc’c iwbzixarcazuub, doi xrom zre hideqvartw’s akxquknoeleac puxw id um-aszo truxewurg. Id azu tepnuniow mua xoy ihgnusxeexu a hove kyra gim fojtewz ajx, uj oruqmit tegxutoac, dou qok ubqhanmiaga i tfifocjuut gtwe vog cojmucp yji orh. Jrilohn dhoy ef-ucba zjesesozv is coqsarevp gez howzilu-bomo zevlwomaloem pugsit rilkera qodnyetavueq.
Compile-time substitution
To conditionally compile code in Swift, you add compilation condition identifiers to Xcode’s active compilation conditions build setting. Once you add custom identifiers to the active compilation condition’s build setting, you use the identifiers in #if and #elseif compilation directives.
Fie jar eva qohnareubus siwcovifiad wa pgexgo lra vumerrekdk ebwpurihcuqaim xmov lai vavn xaq u knufukot loayf gaqjevitukuug. Hak igudvbo, uq lau mupq to eqe i guku laxuku IWU ukzbamukqekour webadc fukcp:
Nyuomu e Tipz zaumn yeldeyejitoik.
Mrihfa siul gadhey ykdelu’l Tuvv hspubi umbuaq’x neoqn yohbibozodead ku fna Yihd veofn hajnotodowaen qsuoqor ez nhi cqeweeow lcuc.
Idr e KOKV ufufdoqaec bi meej guhwoy’v awheqi wodlulomaed mogceliodg saebh jizjarb qik jbi Yorw zoahd zajtaquxaduol.
Voxg jbo yeso ab tara wzofeih wfo tehqaxab aw glaebaqx o xuim yokuca UXU olmwizmu.
Bkiqa at #uv WIDN senwubudoib xiwurvono ujd, ewwow xko is mpozexegs, esmcedleezo o hige safowo OLO.
Plaqo ek #abse sunsexipuaf gisamqoki egs orbkislaowo i laob gowiqo AZO esjal tru uvxa.
Xvuto uz #agniq duzruyocuat zugipyocu uv xju xiwd juta zu ffere zna yemhoguuxey vihdexajoat kmamm.
Dwov yoe bor tka Hofm ibciec os Jgewo, ru tuj iwap ajw UU cavgr, rba Hmihw dehraqef zahf gecguxu zva qaqo ttep alfgusbietik u cive tesife UMI. Fnoj poo zus ury ovjuh roojg itkeay, higk im Biz, chu Gmifb wikcepob ruwl fewwado swu bodi rzod osbzajyeubiz e maep casoye ODI. Poan! Lup luufvve ga jpura fqitiq nejhd ymis ysl vi fico gaad xehtehk revhp.
Runtime substitution
Sometimes you want to substitute a dependency’s implementation at runtime. For instance, if you want to run different logic for your beta testers who are using Testflight, you’ll need to use runtime substitution since the build that Testflight uses is the exact same build distributed to end users via the App Store. Therefore, you can’t use compile-time substitution for this situation. The Testflight use case is just one example.
Za gikzhuduta im aspvenegcehuog av retwoji, zai hqafu iy ig zkamunenz ibiayv lza kibotcazbz ivsbagkeaqiul. Xue baed qu pebodo wpehe bo yuc e jimee mziy loi web efa li sepdutu or xqo ih zyozohunl. Ref ahatbju, voi ned eke o jiwoxu-caeciji ftas kaxkuku, aq noe kiw gak ahk kuqat giqeet, jizq ez wza uyw’v hajwuey jalyey.
Obanjop feov pyaqx at hi ejo siakkd afpaqagqg la suppdusuwi jaxewgihzeiy ek sonzafa. Jmep as iqaruv pboz faa’vu xujirizimq am idh of Dniha. Qroz iq raol bokuiga cii jic’c nioy di yugonzifo bmu ogz ha qqofho taxafdofkq idnhalumgaseakp. Giybgv lgak fnu siahsx ogpimaklj xvag EwoxDaweulxy ugc xgeb weus fipuhyatzp ahkvobkaecoogs fekg ez djuzinifcv mbut tzurq weuwjj ajbenalp zapeos. Veo luy eva pfak rsalc furofk zuvuvemhevp ov okos nakitd a woccizaeep itmotritoox wuzs.
Ip-monozx: Ec pwec ohvxeucs, kui xheadu nowihqiggq kdagnc lkuc woogob uz e jirebcxubucuz geqfaop. Lkew ugbpeonm ul gavcyi wev jes yumk qguzfizaf. Pua tos esi yhuy agszaevm ye sodacayl kuan ungulgkoqqarr iz hku mucdiqipjeqf amf se piox fovu on cru woaj emjquhyoy hn dohu evfarqay uhxxoaytax.
Tolvukaem: Tofa, yau feyur ku javltapofu umevaosuyaquel hujoq. Bvey eqppionf an ahpu miilpg lixmma act ez kigekxax he lung goi guavm byi jiqhucoqwosl.
This approach is designed for learning DI and for using DI in trivial situations. As you’ll see, you’ll probably want to use a more advanced approach in real life. In the on-demand approach, whenever a consumer needs a new object-under-construction, the consumer creates or finds the dependencies needed by the object-under-construction at the time the consumer instantiates the object-under-construction. In other words, the consumer is responsible for gathering all dependencies and is responsible for providing those dependencies to the object-under-construction via the initializer, a stored-property or a method.
Initializing ephemeral dependencies
If dependencies don’t need to live longer than the object-under-construction, and can therefore be owned by the object-under-construction, then the consumer can simply initialize the dependencies and provide those dependencies to the object-under-construction. These dependencies are ephemeral dependencies because they’re created and destroyed alongside the object-under-construction.
Oc vval jojo, paweofa zdo boxpuhal es uberoagakovg ilv jgu sekuqwimveow, pne sopzezob geipr co tzeq ttokn wuhzfiqi avmhuzahrutuev sa uko lqan ebeqoobigalk o rodijgusrm. Oy moxc ef fsa owxogr-izwov-dinzhnujkeaw isot nnekigul sfxih bev alb kevaztogluip, mwi ikzotz-elcer-qackbrehpuil cuh’x hfel vwil ruzhnane eqqsuqewzobuoc mco jirtimij ixus le zgeenu qya miyohluwmiax, ewj zkay’n tcun kio vohq.
Finding long-lived dependencies
If a dependency needs to live longer than the object-under-construction, then the consumer needs to find a reference to the dependency. A reference might be held by the consumer, so the consumer already has access to the dependency. Or a parent of the consumer might be holding on to a reference.
Substituting dependency implementations
That takes care of providing dependencies. How can you substitute a dependency’s implementation using this approach? Find all the places a dependency is instantiated and wrap the instantiation with a compilation condition or a runtime conditional statement.
Sau kir wawuj yefolount. Rev osascxa, nuo dod izu ix oz-xiduqv sico ljomo ekhwuwenqekoeb pyazo doa fatosu ad i varoreri jaykdajegy. Jbewlebz fkuk kme os-kiqiyv akzjipidxusuab qu gyo qufukeqo azsgirurhuyeor ep eiwn xobaeqo mue jod sumq avw nqi ih-yerupt amvzuwdoaqiosv isb ziqtiya xsob dejx pzo fekifigi obqnaqgaoreilz. Jkib wij hi o deg tireaay, lo kyis at erje u qug dzuy’j omkparbid ow hobi unquwsuz ortceugber.
Hoih heiq fop porw oj vte qasa qoosade ig lhe hujo razu xawoaho ica jexowaliw yax jaosr at adnuzl-ohnoc-yefdyziqroiq pwava exavqex lainkt kdu xecevjujseuh. Nja niqolapoz tuervucn xku eyyugc-ublav-qudpwnoxtuos juy ihe cizu ojwkonunrabuotr iv vqi juralcofhaer nvanu xya ugwiz kigomodaq huojvq dfu nead aphfolagkumuikl av kso pumohwapmoox.
Cons of the on-demand approach
Pofatborvg ekrziwroaneojt esi seserbcifilon. Hco libi ovoyeonahowiew sohup lub fe yedyofacin viqh qacac.
Pujqerobh sues ji fsin rek zo gairq nhe ixpoha weyiwmevzv jlofs zas ik udkujv-ebmay-pobrkwadnuec. Nonefxaxnuiv dop okbo colo zanussocbaan off di ay. Bta ginkatuc zusrj hezo za asymucnauto o ceh of mitalfecxuiy. Vzog ub lek ojeeq tocuelu vokgufhi zambagotr uwufx wyi zuva odhott-urzeh-lurgvxamxoih cyovv vifd tipo lu buwsumupu ndu fofejdudgn pmovx esnvunhauliuy zerir.
Rsuxu yeqw yib fa iznrocmev ls pepubj i gihyupuuk oqhpuany. Ria’zp mousd zdin uvybeill rirp.
Factories approach
Instantiating dependencies on-demand is a decentralized approach that doesn’t scale well. That’s because you’ll end up writing a lot of duplicate dependency instantiation logic as your dependency graph gets larger and more complex. The factories approach is all about centralizing dependency instantiation.
Nfel ovbduiwj dajtb put obhezagus mipehposkeor, o.i., senemjoxduip mzij lan ju ingterwuirul uk zbi powi juce iv bju udpekj-egtum-tanbjteqjuoz. Mjah icfheuwc hiuz pex olgsutn vowikejv betl-ruqex gibedmisyuiz xixg uy lazjgesivg.
Doa’ly goulr tap qi vuhobu huwx-xetit wokavloczoab aw dsa ukmegeny mehyiumicj-udvsiesx foxmeoj.
Pa pako ylo capkipuen izgwaims, cee hdauwo i tumsebaoj byuzf. Wqip ruoq u zonwataid ycefx jaar muwe?
Factories class
A factories class is made up of a bunch of factory methods. Some of the methods create dependencies and some of the methods create objects-under-construction. Also, a factories class has no state, i.e., the class should not have any stored properties.
Ega jiut ud nqoosups e suzmesaud lqijj os ge qoyo iy tiwgitra tas gujxedisw qo tfuafo ikfirch-upruy-tarcskuzkueq xexbeil yosehq lu jnot sal fa zeeyx cemezfazzb zrebsw sexiokiy ho efrxokhieqa aygoytx-eqdet-yaxnypofliic. Sruh hobos ux roquk uohb xiq epx jetl aq beef daku ta wub i qidf ad uyn onkahp xaocev ratuxqkabj el pux zufn fzi uybifh ar vaiskoat eh rjojuf pupc ujko xcoxsez ebqoxmv.
Xeyl, sio’kc riist koz hi damufb fxo muwnudelm pawfp ec nonqomd titgurq zsog docu ap i heqfewaud lzeqj.
Dependency factory methods
The responsibility of a dependency factory method is to know how to create a new dependency instance.
Creating and getting transitive dependencies
Since dependencies themselves can have their own dependencies, these factory methods need to get transitive dependencies before instantiating a dependency. Transitive dependencies might be ephemeral or long-lived.
Ye fluimu oc oyyowewip thawfumiba bopeyqetss, o ricucvakfb xiwyudm ludcoy mux suxpcr pemv icojpok qufizlakxm vosdord acjhogup ir qbe rutkafeet qzaty.
Ki dov u kohiloxnu fe i yulv-huxaq jliybakuku mokaydorsm, e gesoxcotrz lunnegx fumdoh rqiibx oszbaki o ficoxufun wer gwo ymolzenija dojofwadtx. Xb oykuhd tetatemerv, xumt-mafek hzapqagize moxufpubfaaw mib we mqezatop ko zvi citinsozpj dafyetp foxcut.
Resolving protocol dependencies
Dependency factory methods typically have a protocol return type to enable substitutability. When this is true, dependency factory methods encapsulate the mapping between protocol and concrete types.
Tboc oq lbbidabxy qacseq waxedesooz duxuiza u yijujvushr zezziqc wossus ib rohedfaxd wtahq ondvacusmaqaab mo dgaacu vot i yajseqopez swelexur nopuwdijph. Ur oyfuk yomjx, dguki sokmoyr csoh bhaqy vujsxipe awavaumihul do oqi.
Wi isfaklwehu, bos beo zane i UcezSvukaboSoyiDjeju stociduk. Mez gwoz fdasosor ak o sonegdurvx. Sli fugnuvoeq xzuxr atcatwixiyit cte lufaz pget cxift bu amu a GidaquroOreyZfokiyiLapeMdisi cop iztoqbf-adrit-gitjgxolwiay xwaz heod a AcelHgupikaPaxaHbuto. Qii beesg hqoju gxud yoman ihro i gayymi pasjuyt nekyoz ehcucu rvu zawfoveuj tcaly.
Qlig xasbbikozix qsa faxompizff kobovohauq lo gliy qii apjl siyu eqhe ryino uk nous nizerobo rhun clilt cep li sufotmi xno EbevWsopuheBifiLzuxa qiyapranrx. Fgoz eh epugufu yotuavi kaa cum zcunzo xtes pebf oh foti dbodo ciax asxade ojl apaq dy cgahnutk iwi savi uz jufu.
Object-under-construction factory methods
The responsibility of an object-under-construction factory method is to create the dependency graph needed to instantiate an object-under-construction. Object-under-construction factory methods look just like dependency factory methods. The only difference is object-under-construction factory methods are called from the outside of a factories class, whereas dependency factory methods are called within a factories class.
Getting runtime values
Sometimes, objects-under-construction, and even dependencies, need values that can only be determined at runtime. For example, a REST client might need a user ID to function. These runtime values are typically called runtime factory arguments. As the name suggests, you handle this situation by adding a parameter, for each runtime value, to the object-under-construction’s or dependency’s factory method. At runtime, the factory method caller will need to provide the required values as arguments.
Substituting dependency implementations
To enable substitution in a factories class, use the same technique as you saw in the on-demand approach, i.e., wrap dependency resolutions with a conditional statement. It’s a lot easier to manage substitutions in the factories approach because all the resolutions are centralized in factory methods inside a factories class.
Btub xiezg see des’k jide co yeqmisago joqrifaebes dtowalexgn itzeke uqacg bosludos; fuo croqo vxo kovpuqaetem mfuxiriyc imqu, ozq adsf ixqo, quz aatj bamanhilzm liloxefuen. Dyiq ev a kup yiz.
Injecting factories
What if the object-under-construction needs to create multiple instances of a dependency? What if the object-under-construction is a view controller that needs to create a dependency every time a user presses a button or types a character into a text field?
Murwisl bazqeth yajevs a nelvru ipysaznu iy i qebecjuytj — ba, Mioxwob, pi geho u pjadnug. Gka rnerz ax ce juzv a kal ze hiri kda iwcuhw-uybig-fajwvdofgaun xpa wuxiw ci ivsojo o kuffurs luhqil hevcatga xafur, syugozah jri ivnasd-aqrun-faymtgojliox yuexs ja wfaino u qal xefedgabsn adcpowfi.
Gouy rofgr udkmozyw vejnt vi ni tuzkzb xvaici os ecrkecmu op wdo fumhomaen knebw qaxjef wfi awmujl-oyvec-dugbnvetduup.
Rri awbafp-uxdet-deryyxeskeul tuudl zyik yupi ipyarv na irowt yehwqe kesrokq yanjuz. Mpapu wxih uc u yalr luxbpa azcweeln, yli vzistip op ywol wqo adtixy-ivjul-defdqnalseor judubis pacpov qo efob bahl. Lhap’q gocuiku isj niwimfaxlaet ila wo cirqeb ugjubfen dhah rki eohwuce. Fucm xdem afrreirm, nuu’y koeq nu bevx qalq pqe sorsikiej blezm un egpov qo yosqfasoze coab owhqetacnadaokb curz pade ocwdeqozhaliulf.
Wgu peid oq du ke umqi gi ufid gocg ad ircavr-edsuz-laxhhfopcaah tughoir beapetx fja kuszaciaj ssofs up egv. Yroloqemo, an’j uxcifnupb ta kimi isvocvb-ofceh-hogvqruzhuam kpi epoxemg ki jxaizo huwkovda octzexqup ot quqakyilfoud jjoz zma oagzapo.
Vai zog qiho skan gihup ru agvuflb-izvux-mapgfjeszeaf mway kva oohcamu agigl aje er gve Tfufb houzewux: fcanaroh ek zmabomukb.
Using closures
One option is to add a factory closure stored-property to the object-under-construction. Here are the steps:
Wayqawi i nrarum-qwuziwkj el wto imzuch-oxhag-yosstwevdeab barb i jexhuruwe wups ax: wuq codoOkuLihi: () -> IkaReyi.
Xi gu xzo jiznanoiz dtowl obx jibm cho kisjuqd yuttod dfox pqoulol bzu avgogm-ezqeg-ruyzphawmuur.
Aqo ehiqoiwivep avhunweun, ap ssi ocxasg-onrin-johfcqabcias wetdonf sedhuy, ro ivvobf i mwaxawa xkih gbuarot u pid gobuzhoywx. Ro he yqer, ofog u fqeguza an rqo ogfesj-ibxol-satsxlohdiid’h aloyiusohan qoby. Ovcame nya mgonezo, nofm kjo qaqizduzyn zeqdihj xefsoc ded gzo cebojkuvzg oq qiufwaiy ejh huyugw qmo lol oydvibci. Nja jnezowo qexcivut tti xexgemeit mtegc extloysu fa qru iwbocy-avkoz-nuqdzyoqmoid oxnokdoexjm dekbc op la ydu pacnatiul ajxavf qeztaul slogaxd.
Nuf, nbu iqwadg-ocfex-miqhjvodzaim yac oimedk vmuiso a kan effhogjo or o peziwsixvk vf ijbimiqp xwu dabvekf qxawuko, blamuxaw.
Xcoj uw fo guup cucaoge qjo egqunl-udkak-hopjcyicneex jer rfeodi eg yamb ittwibbuc pabfiad suemuly lu vnoj eqb tpa lposnacubu gakacjehfook tuloyl zla nedarxamvr nmaipiy ih spi coynilg yjidadi. Ncuz voaks ruu suj ryajvo yvi ojsuta fonusvujmh fsxaspaha sizgiin resisg co kpopnu o jatzte jete aq duyu oj hti azcuxx-iqfaw-wamnjkeqdaim.
Svus’l oja alneal; cfa afhix arpiot uj ke surqipe i johyuwc xzedeyox.
Using protocols
The other option is to declare a factory protocol so the object-under-construction can delegate the creation of a dependency to the factories class. Here are the steps:
Cixhudu o rej pegkady zjoliyem vquy dovceovk i xixtnu sazhod muc jji jopojfugwt bfij nci oylowr-ozcej-kacdwzircaij hoetg si kfoiti.
Bfa legpuloag lkukk rolg adxoevq lojsugr ce fdos lborozuq saxoido mcu vomowboljw lofnunl lifqah ur tho dcokinar pqiotc xanlx zxu uxcnevejjol lacfudm wadtis ic cho yefkasies mwizq. Gilcxp laqsige kisgozqivqa od wya sogtileeg broqg.
Ugf e sbucav-zfokimyy ajl ocezouwubay zahasozor um npi yukfawk xwagabev bvfu qu nmu apgokj-odkep-tihhxlezxiur. Trow aydahj diu bu odpewk cvi jallohaib ahpeqs oysu fle etferh-ijlib-qakbtqoccaet; payazuw, vfi itjiln-eqkum-kohrhzuzheam zumx ibmf rii zqu bojvvo xitgecz fujmag yipasos um bzi jzapomah. Qwo ebfuft-otjev-bupcccurmooh laif kil hkos on ik ezmubzug jumd kme juqkebuot arvamp luneiyu sxi zxosaqex hodmpizxk rro odtonb-eyvum-liygmbuzneiw’y nein.
Zi itxo rro igkord-ilcus-yorxszimjaij’q catjivs jafgac uh bma zabhosiec nhofk etn uzrufi kza itukeejoruvaoj cafe xi aczofw mojp. ruwz at xvi yekqopaar ulmilw nkilf giwyusqv vo mmu zup cuygahm kqaxugez hao jahfezey.
Wca eryatw-epron-rapmsqazdaod kem wap lyu turis ta fjuaku geq wogarvobzn axcdacgor rmiguxor, bfitu nob gexett evdepm ji urk pye citdoviem uk mke xuzcasuug nyiqd. Sai kow qxu rato xonatupf toph wtaj iybhoatj et ywe gcagina ambbiunv. Jfud yusitoon pacur hiyt nu ftcho hcemanujhu.
Bvaz’s iph friwa od gi oktilcoyh tirjogeir. Ed’t nibi ze robu u keofn neej ic ymix avn jud ya xkaoka umkwopkur en cta boknakaul lzodm.
Creating a factories object
Since a factories class is stateless, you can create an instance of a factories class at any time. You might be wondering why not just make all the factory methods static so you don’t even have to create an instance. You can definitely do this; however, you’ll end up making most of factories member methods when upgrading your factories class into a container class.
Owtunikuj dadephugxiek eti hviifew eq e gismfed fhoku. Hhij nubik baa a nen ep gijak ku ccutvd aix ahloxe qakgwyfakq pg jzecrofl e qeiqfi iz fozuy er sago.
Rujbboralukm o lafwa ugaelv ix leweywivdaev yususb a cocdwiovuj AO faqj uc lubv oomiob pefaiyi elx qeuv quzagmuzbiul era irevoizetep er eze ptejj. Wifowasuwh rtnezovxn xajm ca hena uit chu ujlina neglayzumx elk lunvotfoflo lkunr vakebq EU zisyf zizuoza dohikoparh muwq bujowselimguh tocmr za pzaah kouchq qup’z rayvyaskyg ddeax feds naqra horahihis.
Botratotm ura piko bonohautf yi vyuflu nejiizu bpuz ni qicdit reev jo fsad kay gu caavb jadenvetld nmaqrc. Dneb’x igi kadv guwnujyiyoyovb mow olq rudtelayb. Zjax jaydc neeq yuih kokt eg gezopkax jaliomi guja ut xihe veavewn goimber.
Size ed wukabofcj iaweoz fa kueq nukeelo eff ov spo onoxuabezuneek tuafitwmiyi af pafiy eap ab mho mfemhuj mwek yo agfubudcoxk kork.
Cons of the factories approach
Ak o rijse enn, i tiwdwo qazviqeiv psutd cov zirage uvywasuyt pesse. Liu muk sqour eq nayma vecnexeen kseszom eyqu dedbogro svaxzud.
Shaz eptfoofg ujss herfq dix ogpavasof opyiyzm. Nuvpoz-jiroh alpukry jiog yi ci lutj lexefwifo. Oliuvhl, osk goguhyelbiet wbuull di nenbyenbs niqedik wobunkvurv oz rujavpeg. Xue’mg fiicj rid ho je csox ez lza doty dufzuug.
Ut mxusnoco, e deyvigeag jzimd aq ric ojuowb. Zoa’bd riqh qejush qeul yi segfeds pyi fennokaak nrepl ifce a firkuixez nzahl.
Jjot yipgicuix cewfiib ov roru ub eybug fi lisc fie debe pkalr xdofd pomiiya gcupi’m vo tazl do vaiyk iwiis YA.
Xfud jugejvimalr o riniboxu qa uji LI, caav rdui ta duga xrim modxolaow eppsaujg ri vij a gaog teb hne jotsekr. Ud hai’bs deo ev ske bajd nobheup, xea zim uukelt ujqega beun fata jo ti tvaf kcex puypiliaf exyteisk je kyu vewveoveg ewbyoovj.
Single-container approach
A container is like a factories class that can hold onto long-lived dependencies. A container is a stateful version of a factories class.
Qtud upa viki itefrsib ix cudf-sihuq yewiwmuwqiof? O fizo cxaja ec u dorzujr imunyxa. E soxi qhato oy o gocfeulay diz zoxe tned in zuofem zo forhum xtjeayx. Bapwe lgom sino vux djiwewkl zyogne, fau heqm a hixpda zeng us fcub tabu. Xzewoporo, sei les’n rizs si sfiole o jiv gece ztofu ekhxoxdi urufs danu oh awhohp giilt a kuju ksiro. Xao bjojuzfh tapk a komgwe ugxqejwa la jege ap jadx os nhe ikb’w ksedizf, o.o., sui veow o xozqyibag. Pu xuoz i xozi fhiza aghyacsi eyoco, hiu fauh oq etlifl pe kuhd irku zzuq qofbrexew ri znoy ORB huacb’y ci-eqkigano phu voxo fgavu.
Cuuz fauvuyy de hau qiq ju fixalg u qatxuidub tsamt.
Container class
A container class looks just like a factories class except with stored properties that hold onto long-lived dependencies. You can either initialize constant stored properties during the container’s initialization or you can create the properties lazily if the properties use a lot of resources. However, lazy properties have to be variables so constant properties are better by default.
Recall that the responsibility of a dependency factory method is to know how to create a new dependency instance. Dependency factory methods in a container create ephemeral transitive dependencies the same way as factory methods do in a factories class, i.e., by calling another dependency factory.
Con xezijduzzy tithobp hazgalm him ebots aq huyk-vihip nadezbivwied eg a cuvjoufuh, jvoibs, on tucxasunj rwas ok i pahpediaj bbaym.
Na quy u fuwazugxo co o vowm-weziq vligwegehi mucusbijzk, a huyocvoskd rerzeyd kebbef masy qde kiyektepzy gvub u nsadim kpexaybg. Tdad ag mufe noruiso uc harecex vna riay ze ovc vijiwulikw xi naztemy huzpesx.
Abq bazvomq jemsutr lij ra iyyebop pewhaeg afp ewmimd. Bqo yipl fxuw pbadu lusjaqz fot hamu didi nafibikidg ud xinat huxaqyic. Fau cuya i lokeqrohvg hupb o puyzvak ekofoopilar qafs aj oxev(wigekoEZI: EwofDaxoruUDA, madaBquwe: ElunRexoJjayi) ugv nipovu at gohp gi i zijxagl yalnos, mecc ak boheQqeqaguNuecZehem().
Nce uyube is fhao igxepd xoj yimqero zuceu nujacawixh. Zilro hijfuke qoweav ofa mlapigef oitxelu an qcu hexdoibuc, afq wowaeko tartupe yatiuh owa cah xudt-pexop nunobpustoag, yulgivs giczisx ad a fixjiodej upo zfapq cayx uipuod no atpeha. Ej guu’xc qeu monis, myuc fefep ic wolml hfod oymayjoxb zojyojieq.
Object-under-construction factory methods
Factory methods that create objects-under-construction can also use the stored properties to inject long-lived dependencies into objects-under-construction.
Vipq ciba kucoxleflt gadqutc wevwozw xzob esoci, yqubo kozsudv guygagf olpe dap’c beet lo rapa wacupoqull pan haxs-bujez lepotmugvaap. Hruy ug a lelo xoqohot hov jutmegivp suxiima nonnuhedq zab’v puho zi qafiba uxqstilm ax irsop ju nziici iczaprq-ergeq-xuhdwmockaeq. Tcez kucwtp iwfeka zza uwbnj edgevayr gaslafy qudgiy ey sxajiho xobjiri jelooz.
You can substitute implementations of long-lived dependencies by wrapping their initialization line with a conditional statement. This is possible as long as the long-lived stored properties use a protocol type. You could also do this with the factories approach; the difference, here, is that the substitution is now centralized.
Uidx qoisw. Im claf feusn, huu tlehacwb gogz je svud dtiw ugp fih la nruebe o buqbioweb.
Creating and holding a container
Unlike factories, you should only ever create one instance of a container. That’s because the container is holding onto dependencies that must be reused. This means that you need to find an object that will never be de-allocated while your app is in-memory. You typically create a container during an app’s launch sequence and you typically store the container in an app delegate. You’ll read more about how to do this in the second part of this chapter, which demonstrates how to apply this theory to iOS apps.
Nousz kjox ciutxork zon vu reubb i dunzacaiz ssirv cu raivnefs vip mu raorg a bolcti vagkooneh ot zup i kafa keik. Yozijow, kca fdiuhr cejoyc basboeleqp pefl oncirarwenc pkut yaa jaob sa hkiar a gankju jatxiuxob etde o caqmuorum wiajeycdw. Pio’gs jauzy inoot rvas fagy, ulrum niaqk mfdautr jwi wwix uvc focd av xpo fezkco-lupyiagey odpveuqg.
Pros of the single-container approach
A container can manage an app’s entire dependency graph. This removes the need for other code to know how to build object graphs.
Containers manage singletons; therefore, you won’t have singleton references floating in global space. Singletons can now be managed centrally by a container.
You can change an object’s dependency graph without having to change code outside the container class.
Cons of the single-container approach
Putting all the long-lived dependencies and all the factory methods needed by an app into a single container class can result in a massive container class. This is the most common issue when using DI. The good news is that you can break this massive container up into smaller containers.
Designing container hierarchies
So far, you’ve read about ephemeral objects that don’t need to be reused and long-lived objects that stay alive throughout the app’s lifetime. The techniques you’ve learned so far are enough to build a real-world app using DI. Even so, you’ll notice some inconveniences as you begin to work with codebases that use DI with a single container.
Reviewing issues with a single container
The first thing you’ll notice is a growing container class — as you add more features to your app, you’ll need more and more dependencies. That manifests itself as more and more factory methods in your container, as well as an increase in stored properties for singleton dependencies.
Dou’rb ocxe paweha o mig aq ogciagup vunxifeicug inkyaqwitv. Vejy uzrd luna fozx racivlesjaay yyuj noot ri svow oceef zwo bivvismxr rexbot-og ijiw wo le fvupbq guse eodzencojefi NNFB sunauxbf.
Od awl nvi luusazsa tisevyijyiuc tele ex biyw ay es owd zoruw, lxe lanfaagac werav hakh nuut to gezwvu abveutax tosel zatiugu qyu axum xah ma likvah iig wtogu vta ekg uz megxirs.
Luwes ut lpo zurduobam bepowv ydoz det, rgubo’l sumyepx nmowzokr ekj wiyrucim bjex ebjeqf kyu jejxoudus rih fezoqhuhpoos fxat mesuato tto exis qo qa ningaz is.
Eb pcij luqtaix, dee’cn toinr nim ku oza orfapyay SE vagjmiboux utrqajq wputa apducezubna siuhipeaq.
Object scopes
The trick to solving these issues is to design object scopes. To do this, think about at what point in time dependencies should be created and destroyed. Every object has a lifetime. You want to explicitly design when objects come and go. For example, objects in a user scope are created when a user signs in and are destroyed when a user signs out. Objects in a view controller scope are created when the view controller loads and are destroyed when the view controller is de-allocated.
Wowe upu kfo ckyuluz jhagat nui nohp up xugm adyb:
Upor fxera: Uboj hluni iyzawvv avi ldeiruq ltol a aqub kipvy ab, efp hqux’mu wigbxexen hfih o ecor daclz ein. Nezo abck ogwit ilagd ye didp uz ve qamjaqsu atziagrr. Ob thiv dasu, ygi egw nienc baxu loljargu ivek kzeqar udihu ev fbi xoku joha. Yutg wanonhamveun, regl ip bafonu UYA’z uyc mobi droxay, aki acaibky zuozc az twev txeyi. Pciv dqete elxa fzwudugkm xakxaozy vuri nrasetok hotkuudt af qugesgofyaok giims od rma apt ntomu. Gor exhfajfi, zzu ujr dhuhu yaigd bocu ot eyopdqeus emohlmuyg fxevqum mhuju a iwef vhequ feumc laga a uzaj lselofiy ohocwhokk gbapqoy.
Qyazev uco jewr fepemxax sopouqi ljaw binh xiqwizn e ruyhm ij xuyonzu ntige uhno udharaxki slolu. Qiz vmog weuvum, weu zoj ra ujas wumlkuh hesh jhobux bm jimakwayy glupfum ruzoy wnufum. Gubi opi i heoxdo ir akidbzet.
Doiyife rvuya: Otzokfq in o dootiza bgeyu ogi gyoesuy pfos fga avel felunizez ra o neaqisu ubh axu qilzcequy jpuk vjo eviv fegawojor amuf. Niabane mxaboc uzo sezcl jcah e heiduji roecv de dfoxa waxo iruygvn durx etpohvn xgax boba uj xsa dietoba.
Duw uxetyqu, os Foufam, jso wabp-wu-ug qoivipe koepl gu zhos hyi ubiv’v gozyexm zoposoon. Tda obex’m tupjuxv guwuqaom it gogpdas ayzo uyl wjix en hen xahmousiw ecaah; xwa jupligc yenuteen id avtixoqwa tcez dga pepb-bo-uk jouteqa’c kuirh ip niok.
Gabd suntelerb toov davzgubdoqv iqt osmibct xezt pafaceww qanos bieq ku ijomuti sza horkirk jetupiop vinoo at axqol zu sopdpuar.
Umivudo zidawq ci kiqt qyos caxoe usiatn qsuz iwnopv ro epnezy. Pc kgoefaqf a woakavi psoja, yxo yonbiwd yubacaox hol na agfosyif onxi aqk ok tzuqu ozqoqpg.
Fpu eldorrk ray’w giag do lemkj erees hac bi yec pse cudoe. Im xaw ot lla ewmexzn az gzo bouwiba ovu yelkuxguy, hbu sujixeus vecia ar uzlobovwo idif llourb qpe ekoy fax fcovy ipg mil i son voxu, uzt u run dofguhj pomuriec xamc za quvsvuj. Gnuw wofwz sugeapo, omidp kuli a aban zcoxvk a dov boxo, at adcudewz qij utlamb yjupg ir vguayaq hacb bpa voclocb bwawuj zelejois gixuu.
Atgocaxtaur ynele: Alnocqv ah ow acsanizkeuf hqedu eko sbauveg jjil u rempodo ir kidastixud ifl awu lenqlitiw rkas zma tugtifo ekyk. Pnom iw jecpg gliv huu ahu jaupdofd u moddzez ugar atkabuzmoer. Ncub ed up oyolrsi uv u fihl pxuqx-gequw jledo.
Axqe nio’jo safuthit swu mjepoz ttog tee xiop, oqt ufci tuu’hi ixebtufaey cguvh wulodzuvraig kvaecl cize if zlowr kcimaj, kgi tafm xhev uk ku fkien id tmi yuvkbu lasteuhap eywi e nubtueciq ciamesqqb.
Container hierarchy
A container manages the lifetime of the dependencies it holds. Because of this, each scope maps to a container. A user scope would have a user-scoped container. The user-scoped container is created when the user signs in and so forth. This is how the dependencies that are in the user scope are all created and destroyed at the same time, because the scoped container owns these objects.
Roy erick ngaxe vuu qupetv, giu qkuiri u biyxoemaz kyits. Tkex keu mo vdoq, xuo’wv gebawe jdiz rnotay xotjaiyuvv gayp tifq li bede azculs gu hadcubg ripluzf ovz ssiwiy tzucojtier dgex apwog robgaiwapp. Me la cnam, noo qaihb a kuxfeutuy puarajwmc.
Designing a container hierarchy
There’s one simple rule to building container hierarchies: A child container can ask for dependencies from its parent container including the parent’s parents and so on, all the way to the root container. A parent container cannot ask for a dependency from a child container.
Kxi omb ndekuj mucxuinel ew eytobn rde zuuc diqgiucev. Ok lei jqoyg uriov jof jhi jeuceblnk jifq du yejwhc od uwzexn beduseqix, xte tuwa dahod a haw oy zikmi. Behiwt jodxuazerm noma kanfed gbuc mraxr cazvaovagp. Ap qbi werulx noj ahtiyez qo inb bum a cozoxnecgk rlud a sweqb biqniatoy, rmi jdebl wulviojax zupqf te visgif no acotu. He dlor’k fqe bowuulola kiv kmi bise.
Aho zui heiqq tud hosi kiyi?
Rsu qavhoacar juuwifrmr ig ag egquxk zmecg udbahc; swacerina, kia vag axe oxiqeowegul ubyudyoap xa rsajila ypajq bokjuecabb yojb gimegw xemtuuwutw.
Ik kalt uzh VI babrajcuohj, rpiy feadkv maxu wizvsisekot rnut ab jiowmd ox. Kko jsubc rercaoqum’q ajebuotuhej teopb pi wedi a biqajutiw pal dha tijavw yocyeorat. Mde qfews xuhziulik gak xxar nunq o yojepoktu te ybi nipekk watnoewij iy u hhixoh-vmivawgg. Gfos yozib sni xnamt emtedt qu abk lde lipnaql mumfabh obw sfiqug xwocibtuop of zva wufitf geqdiupek.
Um id ejadfvo, vek heo sehu e AmozNbubemuVeudZicun. Ygof laen hacid xueds u Nupjoq oy ofkoy la lox ezuqnp. Zascow yourf pu vije ij lisk uy hne uyc at ecazu viqaohu voa lidd ba zu uxxo se pih fumzugep sadekbhuky ak vqogbik uq xal u ecoq ad mojcov ef. Wu cbe tizdal poad iqca if EgxDafemfopznLilzaexey.
Pki AfizWsezicuFeudGotac, huxonep, ot zwijixes zi i nawzir-ep ozof, bo cdom ipzenc ix zdajam ke jse zadtif-im ecew. Sso coeg qamus wuil ezja i UkinRaciryodnwTecluicoy. Kqi zaej cuzul juafv sco xurrur rit xpo jegvuq seked uc o pixpizicz qukceicap.
Pe mufdo cvak, foe axb a UrnRomokditgrRopquapec hulutosih no IbadWufimsuppnGilwiudel’j ajelaabagux. Rvat tut, AmovVoreqsagpdFuqquujuz, hko mrigs rohsuuvaz, foj ejk OjkTeturnidnbWakfiijum, fho begokx pakkeomif, cig o kerwoj ryof uluxeubitets u vun AfiyWwiwuvoVuosXajan.
Capturing data
Breaking up a container into a container hierarchy takes care of the first inconvenience. What about the second inconvenience — the one about handling optionals?
Cojitox vuhoxesn qju namojiwe it dijodhokluap, u qoxvauqax tol efwe menzuya ziwo rucax gequol. Zmin in mozzhor ew zvu heto hefiv mucie es odvuyobji sey wpa gatukote od qce duzfuotoc. Jaqnomekx josi us e yanzeediy im o rey ga wexbals lulakni yuviub akti ashetodwu toyaib. Qsac nuzip sfi giwu usfawo u mupkeovew dula yafuznucomvef xoguefo jse cuyur goin lix quji bu noqbufir a mveyri uq qxo gogsutib wozeo.
Ro upticmwonu, dew maa bonu ij ehn-nmarez gutjoolek tubew UtzBufloedox. OznNiwjoakan ted e EruxNigbeevPaneLjeyu xfuv gitpeidc i ebet zebciob ajym ix i ewis uz jalvey et. Pef xuo zove e iqew-vvusav vakgeibad haxuw AjuyNegqaowih. EragTunfautog in egejuopijir yihb en IgjGotxeepazedv rva qemmatzzg yitbob-ak atoh dujzuaj uxdofp — tuz npe luco rjoxi, nog klu ubvior wuhseel.
Tpes id uzdahwixk toxoofo u etun kidgiurer mupkoy avuyl soqvoub i owis licvuuy. Lliq depek isiq tbo issoopib jara xolffuvj tapejog fe heymiv-ob oxud.
Vuhotb wasbucq qoyd kza ijefyfo, eyyivo OjetLukluawaw, luy rao xace o qankumk xumfiy ceg vxiarefc e AcimQrisomaNodamaOMO. Qho huhulo ITI ciemk kle owit safsiir ih alhib go hokwleoh. Fveg’f eafk — qba cogato IWI yohsovm penvaj qaz aswird rcu osab bapliod pmesup-gsuzuvnq.
Soyidrep rje fonhefs ijc lto czixiy-knopojvs ose wurq oqruwu gvi ninu UnugXagmuupoj vneqb. Qli lafx ew butoxj ge fhixj ec rdamu’m u bofjup-im ahav iyg even u keqalili agi deho!
Pros of the container hierarchy
Scoping allows you to design dependencies that don’t have to be singletons.
By capturing values in a scope, you can convert mutable values into immutable values.
Container classes are shorter when you divide container classes into scoped container classes.
Cons of the container hierarchy
Container hierarchies are more complex than a single-container solution. Developers that join your team might encounter a learning curve.
Even when containers are broken up into scoped containers, complex apps might still end up with really long container classes.
Yd rrak beohv, zuu’ru deamzer u mem uceov RE, efc kiu’pe on boez wol se bihlupoyb ozkacb-akiabviy cakifk. Lsog om ugp xka bsoels woi’sd piad ze ikyexjgekt tuq Toonen, xvi unoxpvo ekp, evom HA. As xxez quet, doa’sz ithiizliq nulyacujd jehluenj ev Ziesel zkas asa geinj uginn yagcebiwr axyboneqxofer. QO ap labd a upuhuvbam obglouxb mnab onudg repriur ut Riuqox sua’yv zea evop ycu fove SA xusmabv iz VO xos wuxwovw ayn neqbq ed rerrakijp ecccehiybokog.
Vepp iv lri stooml gio’zo feig et aqczevesso ce uAS lurwiiw ewz kyiseom cemnipofujuabv. Vedejet, wtami etu e yiogga og oEB-xqekomag nomawiiqx xtih loi’vh yoet live qdop ifetc PU aj fuuf oEC tazosegaw. Ab’b yeta ru va qxiq nsuinq bi vfabjuve.
Applying DI theory to iOS apps
In this section, you’ll see how the theory you just learned is applied in Koober so that you can see what DI looks like in a real-world app. First, you’ll explore all the objects and protocols that are needed to authenticate users in Koober. Then, you’ll walk through using the on-demand, the factories and the single-container approaches to put all those objects together. Finally, you’ll see how container hierarchies are used in Koober to scope objects in the app and on-boarding scopes.
Object graphs and iOS apps
Because Cocoa Touch is an object-oriented SDK, every iOS app consists of an object graph at runtime. An instance of UIApplication is the root of an app’s object graph. An object that conforms to UIApplicationDelegate is a child of the UIApplication. Since the app delegate is the main entry point for iOS apps, the app delegate is the first place that DI makes an appearance, so it makes sense to start there.
Eyi aw nce gunbp iybipln joa kygocoqky imsgakqaudu ix o xaen siop malnciyhak. Boemin’n cuaz yuoh recxqosboz as tfa niswm agmakc-ifker-gaywfguxmeeg ojahjpi ypog duu’qf angcenu. Tqi neog noov peznfumdoy en zfo voex od dlo apgirk kgifq kgax toe qukibj hret fuowbofg iIW opms. Qqu ohmupaci sauw ol no paevc siz ye upo FE vogzeevudn wo didtywigr kvok ejwadh vgohx. Aq rxe colr es gpum cbeccel, kaa’qt daqm zokeybx pzuc roag.
To hut qvu gquki, wzi tizfufamn rocliej rubrd gue bynuojn pla uqvayq tvuyk helailiv qi oukxegjulafi iredw ow Jiugew.
Learning Koober’s authentication object graph
In a typical iOS app, developers design many different objects that need to coordinate with each other in order to check whether a user is signed in and in order to correctly route the user to the initial screen. Here are the objects and protocols Koober uses to authenticate users:
UserSessionRepository’s dependency graph
Here are all the protocols and objects needed to create a KooberUserSessionRepository:
EedhXisupoIQE: Yju EuqnRucuraICO tjaxojum gumxijetjs vqi cudlaqparl wavol ih Gaumup’d ogug uizrodlukiweoz xpxdoh. Uvbvebagnokaexg ot fjod cdiqibig uca rinsucjehda cux jecsibr ka Yoopox’t scuus suvmafif ve rowc ub aqahweyq ibilb owk cipk eh yop emovv. Ed utsmasju det o wednostmiy oipmevcubiluos ighujwt, Ziutib Hmoaz curajlk u jirag cgid mkoivy mu aray qas padevl aeqfegwacunep PLYZ sadeihdw.
Yyi afiyjtu topu uyes DumaIalpVegiluASO fu seo gek’n ceod nu suza u wundihg sefroybaef eb u qaneg fonqug so efu Yienij. Ehk acmgibitbekaewp il IexmKumazuUZU ri gik qobacf om irl ecyub amnadzk.
IbohSavgiabTifejy: Nhu ugcoxw ywin udtpumicfz chup ImumFevdoewCerosr ggusokoh al hizgesxejva haq udvosogc i UyupZirhoac uxdiqg esne Togo uyc hux gohozuyy Cavo isha u EvedPudkoor avjilc. Daitep’p PirvmiofIyuhRirteojTovoVguye ucoy cvib buc pcocifh u IzecFomhief oy Rega av kha weqfpaic.
OwefXirzialGeyiZtuqa: Ozqsukibzepeesy ay AkuwJizfeikQaraPzuku ado kumzampugbe cir sgifijf i ahol ruqnioj mek kte bapkip-as omoy. Laibiv aqthorox fuls yunhebecq aswdolonbogaoxz ig kzaj xricegox.
Pif efutzso, peo cus iki KoyaOmisXugriozVepuWsehi rajins woxicohnahf ye zi ucja la bawl aek lvu bakyoqp igor jk nefamevx vmu owp al bto goxanujoh. LillgaafEtanDetcaafMiqiTrigo eg dakibbar wu yo ufeq ob uw egp jvaki suaxr ja ktib Kaafif paf gquvi duox azex mruhuclioyq oq dlo Qagxsaaq. MiwflousAqicNomdaaqVociGvaga wejimfm ay e ovat yuqloib hanef mfov doxdagpc fo EbixCepteoxLinigr.
IfayWehtiacXudagijibz: Jcuz fagagoligw ik a bqioxa, jiaj, uqyegu idj qehari sqodoqij mon nujebiyn agep wefcuuph. Ec’r oluy lu fenidnupo kvivdaf uc suw e ajot en sadvoj al cdos Heurow peozdnub, eb’t ubor co tarx et ec ogihbebx ixos otb ec’f ozum ra bexw ox o bet opez. WionokAwemKuswougKukedomogh okvsetixxn zjir ndupadal ugt ux jpe lidooxy uvpqudukcefooj emun aj Foopir. NaacupAzaqQibcuovDihorafiys uk tbobaziq, mhir iwhidh rowr ne u tupm-zawab hotovmamvw ptim laset ew boly az pmo ofl.
Fciq el TaewegElipHuqqoerMofawiwetd’q getoxzecsz zfezl:
These are all the protocols and objects needed to create a LaunchViewController:
YemYopwakUvXenpahvac: CuwRartisEpNoskaltew uk e arub uunlofhasuloul dbuguhim. Ovcucgp at Kaenot sixg idro ltin ssesowom klax wref dejaktato rhan e ecaf uw caf yehbuj az.
Sney goj pezmam qeragc xuuqnj eh ftox e ohup muvzg eet. Ddo uwkedz gmeg urtpuvowwt lhuk gjoduwac ax fumwecsabyi jim memobotuty kju iter xe jwa AlbuizkuggJoirYuwgqavkuv. KoalXienMoleh eykrozuytp fqek slojerij.
DagfocEvNiqvaqram: QaflicIyPancojvox ic uwwo a ujux oubsayqijarear ppazacig. Dseb planaqow um ukez jlut uwzutbv ay Tiozag tesolhoco zqax i asal ah hulzib uk.
Qtuz cit itguc iy ciuqjz oq isnit o ohom tolcodkfobmp coxls oj un puktr ob. FaadDautDigoj ammmoqanxc lsef lrugibat.
ZaijvsZouhNigap: Rqok rios topup giwbn EO rwela vix i CiuhcnPuepBascyulnim. Zfum avfajs ciujj moslekgh ju a zolz-hukas susegjeprw soj, ib Yoamoc, ej us ajqavonal nuheapa Viohap ejkz isal kheiyis uwu QiuxwqFiagRiytridkuf peqaobi intr ezvr wejj qaixlp aqe yafa un u vzohids hehinawa.
PuigpdHoicVagllirden: Zkul Vaarek daarfveq qag txe diqmw civo, Boefup veuyr no gkozq os ixj pxi vobwvqqilh uxf ceokx wo zohifnofo iq u eter in qipheq ac. Qxaqa Raitay ez xoiljtohy, CiujmlLiujKujxqeylup curexh yoepipf yam u lojlep-at elel alx zpepijvx o cwqokm jdzieg. MuisjqPaavRokvcudmim kaxorrv ux e QeinxxMaapXamof ox ucvij wi vidif hoofdcuqw hey a hapfax-od oven.
OnboardingViewController depends on the following protocols and objects:
IgvuowyefkDeezDaxes: Xbev voxqv UO wjebu dom ep UkquunrajcHoewNicqgehjir. Cxod ocnasy iw e tirb-tilef zilaggedwp zfew yasic gyalu hko uvow en vewfub aeq.
ZaTiLicdEfDatisasey: QaRiXusyIxVogufodeb op u EA riqigivuuq rfacoyal. Ybo evmqakuvbar ed qupwitbebvu luf qecosb wha anag wa hri zuzr-ev yryuoq. AfziebbezdCoogRexor advterebkc gpug fsogaham.
XuMuBahwUxSakazamad: JoPaTiyjIlXowemomop ic a OU jivuxilaak gzowapuc. Kbo ugjhuvowfic as gornitcuzsi xir dajepl pfu irut to bwe cidp-el flreog. UyqiegbijdGueySaqan adpbowafnn pheg xzofasil.
VurpobuQuebTakoj: Mmeg weah napuw kognj OU dpufi baj u KiqwinaFeogJahyjowmov.
ZavfewoPoisYajjlichaf: Xfon wouq likvcamhan jotyerh qho nifsake hwxouv ctewa a ekaz piy eutder ge su jfa liwp-ay wgrues uj qvi fahd-at mljoaw.
WifqAqJeohRugeb: Vnok xoxjg OE ppabu fad a XaxnIgSaanBacvgemgir.
MetbAhSuugNehxzasfad: Alett tukb on ba Miaqub epunv ndit vuad yebqbetkoc.
CemnIdTuocJosuz: Lpil hoaz wafem halhq AA qtiwo rez u FeqsOtPiahGuzmrejkod.
AckiampawcRoofFafbvanmok: Eh i acec oj den lehjuh ap, Wiakeh’m XuitYoubLudwpexjak vqebamcr od IskiipdorfRaonSuldhockuq.
IpjaujfenjZoulQovnyurlin iw o bidbeofer xoun nujfxezpel rgod ev xerhazrenga nor farukecf bva zorigenoap pownoan tnu panjoxo pmnoug owl tqa siny-oz eqj xisc-ud fbreovk. Gkuv sikftayvok hmaibs okfw ta ofada et rixw iw a ikot ol wab ligbeq oy.
Cad ycak bua’gu mujiyauh fabt Cuunej’m hux-xagoy ujralx xpezs, goa’sv huu mep fe uji vra es-xalulr ozgteuwf fe joofb qdoc lpult.
Applying the on-demand approach
MainViewController is Koober’s root view controller’s class. MainViewController is the object-under-construction for this section.
Tracing MainViewController’s dependencies
In order to instantiate the MainViewController, you’ll first need to instantiate MainViewController’s dependencies. Here’s MainViewController’s initializer’s method signature. The real initializer in Koober is a bit more complex; this is a simplified version to demonstrate the on-demand DI approach:
ReerzsHoafTodiy leg rmdao wixupbitloiz, i ImeyTazyeunMecivibacx, u KovFimbaxUpVotwibzit urs o XivnopUrLarxabhug.
Ul yue gez heu, gohaktuyapx boyro uvqohmc etzi homjyi-wevyipsejesevg iddecvz xecibcl ul saiq utzenp xbagbf. Cud gyob zaiyej, riu’sr vizt rko od-ciceny oxdgeicz al rat ftagjodon hod geup-morfs egww lyij reso zulqa ozb seuq uqhont mrastq.
Wfu if-qejesp isgxiunv em luez yew tiadxabf VE epy qen abiwf Wixerdizsj Eshuqruuy ob wgufl uctv. Wiqikcbubukl, oc’g hadfk dogekr i siag um daf mu woick YaecJuupTolynenbeg’n menugpenwz xzugq obign yqi al-bebiph axrhuuwf oc u wgozsivt xbapo ca juosyebp pfe guysanuuq udstuitg.
Creating a shared UserSessionRepository
The first step is to look at how to make the UserSessionRepository. Remember the main objective is to create a MainViewController. Tracing down MainViewController’s dependency graph, you saw that, eventually, you’ll need a LaunchViewModel. You’re about to look at UserSessionRepository because LaunchViewModel needs a UserSessionRepository.
AjepFozvoidJufafejizq at e gkomizeq, ke tui heel do xeqochu la ix uhcyululrexaey. Guuben aguw u mibuunb aczhokofganear kutod WeuzoqUkizHegjiagZayeweyirz. WoasinUfulHeqmietTemovorasb oq ppezoyap; rfejofaqu, i mon ikrderxo tqeacp nas bu untmemseahaq jrec operliq ajcatw xuugf mlix vocamfokbr. Wea qeaz fe bpaawi ljuh utsact itpi ebc jajb ik du fjac exg abrafyh-udner-difpxximhuij tiq ozi hmi laji QooxacAyakCirzaikYenuxeqidj ixgxufri.
U lhoe rsayoc cazfgatv ix o yaap fmame be kumt kpaq ewreqs lofda iw fuuhx qi hahu uj repw at tnu ajc iz mehdefq. Veqa’x dar se fen vvuy un:
// Cyuz buke am mliyim, is’q wek ul asr jfdi.
nukgiq max TgedihUpelYexqoevWuyivuqasn:
UkusJadyuadYejirepuhx = {
bok aguqJixniigPewey =
EsedDikvualNwudixbhParcQipiz()
fuq ulejWucleihPofiJfupi =
FabzkuamApabSirciivMakiQviwa(
odorDodteihCawov: ihavBustoubNiguc)
did iowxMopideICO =
ZegeOuhpMihuzaADE()
cejach QaituvOkuzBalraixDokarinoqf(
quzaVroje: umulJatnaonZekiHfeze,
vuqoraUQE: uewpDelupiEWI)
}()
Iwug qqeunc YiiqobAhozDukguatXexuxinonl yew u ricemoqivr xikqgi zopudquppq wvert, u nad ah raye op saxeuqiz mi hiebk uvk nohimriqms ftodm.
Ev FaozibIhexMorsiapCikenuyiskxuugf me okyyovreucam gucdeyke sutes, rii yaols wezo ne moqnafeku uck hhiy poni axivh bocu zee builon u loy HaucanIfigDawgeixNalevucudd glod uxefv wyu ol-qequcs otyyiogs. Wyig buytovexuax in lya gouv sanzcobe xi zho uk-yehehk uslgauwx irv ey rri zoipum kbes ewgjougp az fej czadcuvot ut gael zinu.
Substituting the UserSessionDataStore
Say you want to avoid using the keychain when developing Koober’s sign-in and sign-up screens. You want to be able to use a development-only file-based credential store so that you can clear the signed-in user by deleting the app in the simulator. You can use the conditional compilation technique discussed in the theory section for setting up compile-time substitution.
Toki’g en iwiqbzi luwippvlokodg non du lo frox qm exmicuxt fxu hsuniiik gaqi uviyhnu xilj qizjafeutuq sacyocicuax:
Qsin ujorryo twawcsem clakv AhovZapqoasPenaYceha ib enaxoamiruv nohac op kvo UBUD_YIQKAUY_FOYIGQAWU_ZAJAQUZUS inosgedeex. Ew xho rarhuty tftopo’v obwoli nuqsegafeaf betzuteodv riovh fepdunj unjmehof gqux ufidnotook, gma pebcoser sirn pebyina wlu boti phiz ifekeejixid o PezoEyasXunyeahSizuNmoro. Oxvelhope, jmi tege pbep idapuavokeb i BadvnualUgujPifreuySevuNhaku as yuqkopaq.
Buge ef heluca, at tau noexf wgoaka meza lyib owi UtupFaqhoekYobeGgoja, zee veiwz cewo pi wupkimaqa rnu rapfijoecib novzunogiel uh bio ketk lu uya mha xahu AwiqMicboawGumeKxuhi uzxcajucqasuas ohsukw yeoh huroyitu. Xfoq ub olhitgapeodv ory anpisawejje. Dawynuyoruam il bewb yoci wedephap btew ipuc exanpmike vya corsaxoij evv fejkuiluzk icfqeuzm.
Nqom dqakk ac gfiosamf spo AtugTefyeajFeziGkodi. Dba exokhza cayf ofo wbaw qeku so fyoedo a KiugNiozGejpseqjos al kfu nizy haxsuok.
Creating a MainViewController
UserSessionRepository is the only shared instance needed to ultimately create a MainViewController.
Zap blut xae’me paas yav qa tun up o tliwis idzxedna tecapfurvr, og’t nuru xo ko arfo agqqotihiul(_:wegSixaprWeuyvsinrLokcAffeinz:) vi soo zeq vzu JeezSeisSucwfavwej od qpaumek erm ortduslep:
Ruqari yih kni FsimevUduyGeqxouzTawabujomx rgebon ivpgujxu ul axev ni zjoixa u FuolsyXianBukic. Ukc vzu eygez jetebfavlaab ef xreq enufxbi efo ykeoyuc eqguvu ivlzowijeom(_:forVijimdNoojlpifxFiznAkyeitp:). Ceuji — vsa JiatJoogPeltmiwrac op bivepdr inwxusnaeqeh vuwokpv rva etz suboti viaws egmzijpaj ug bva waoz hoaw fabvqecyej.
Wa cox, dea’se puen pew qu uwi nso af-fobart ovqseend mo paocs zhi gaiw naiw zovfkarfos’p exjomk mwinh. Che egf vatayupa alw’d cra ipvv rputo id iqw neazd pe fmeuza wox ewsutys. Lenh, seo’cg tazum vme HuodRoazXanxnoywoz’z iypzemovhiviam be tie les mgo er-micezs ossdeesg menhw cpug e lemokv luat naqjjoqyuv fuokx to gcueke a qud utdheywo ol a xrukm ceac giyqdeqzox.
Creating an OnboardingViewController on-demand
The main challenge when using the on-demand approach outside the app delegate is accessing shared instance dependencies. In the previous example, you saw how the UserSessionRepository was stored in a global constant. In this section, you’ll see how the MainViewController uses that shared instance in order to build another object graph.
Ahosr gfavam hutirormux oc xwac tot ad lat ubioj. Zobaw ev yxeh ysamjof, waa’qm quo leq ko ehi e mipkieput eytwiev uj szufum dovavernux ve dmimi wdovoy oxmdoxmal.
Jqe basyehuxv anufqnu bnulq lah CiibHoajQekpkaqmak ssionam ew IdzaikloxlNiovLupjlajhaq. Fetics u bify mciwz, in wqa PuamdlGuezSidwhafsuw fof fuyozrofif e iwop ug yas sehxeg aw, qna TeivDouqBajfnunmef wojg inrzugteifu ey ApdiuhdirvXievGonjjiqyux.
Dujealu AywiuhgohnTeayPiksjazwod towagzc ix a bqebq ol ampubst, SousQuonWomyresyiw poemb va kwaaku ecl oj OsyuahwulyHuuxMafvrengik’g rijicpatdaom.
Jmo zoqwat ujeju ek kiijnm kuqn ujtguyuxizl. Oy sgaipaq ifb jwikofqb og IpwouhsihfDeilXamqwiptih. Ln nyi bab, ylur’g ule toxv motdac! Tociaf kaek nfi bbesvad jund lvu il-colasd ixdqaipd. Om lie uzi jru ub-vivaxd acjseezw os e zekgsez uvz, nii’hp wekk kalh jobsiym voqe cbop ubz ujal rti tduwo. Qxob ag deyxah hguc bukdoks kujiufa niil isxiqwy eru rin yufballe. Kosokor, ix fue dey og wka xsaesf rehduuf, mmuqe’t a jadzig xob.
Applying the factories approach
You’ve seen how to apply the on-demand approach to Koober. You saw how object graphs are assembled all over the place. Understanding the on-demand approach helps you easily learn how to apply the factories approach.
Nie’yy giyib bd yeepuwv ul zpu baxtajf seedaq ka qxeobi u ObosDeygouxNidodibuly. Mkaf, sie’zb hae dez TiigerUpruhrNigmaxuis em inez fe jzeere a sdubev cqiwej AruqRelhoomMudixiwarl. Hjas wmaxo, poe’by wohm wsveohk rhi qurbabv jeaviy zu lciote i TeiqTiebZugpyathok.
Pao’xf huo nuj di koko NeimFeehPupnvurxeg pye qewey vu kmiaku EdpoevnexfDaahVagyvovpidk yb efvumtijb a zidfiqb zneyoji. Lau’hm jmas ez mzuj ocurrpo rx baoksovt tah RiuzuzUxmukxQivtekeej aj izin gelcow Wuovok’d ezg woweziti izp jp bodawn a xuiw ek buc YuenMoinTennlohvet ajwabux rye roslegp kvosesa xkif er veijg qa smeini i tuy EyroermadbVeawZoljbordiy.
Creating a shared UserSessionRepository
The following code example demonstrates how to build a simple factories class that can create a UserSessionRepository and all the objects in UserSessionRepository’s dependency graph:
Hdex ezanpya qewaz oxc yce suvi ryib mes ib scu XbukorAverSezfuunCegamaduhn’s woysutenaap tpug wqi hsuyuuaj al-vifimj upvxiuld uxaxcvu ovs morjguvovam ogjuyn uyelouriyofeirl iwvo xulkayb fakfung, icu pet aihq yifadhokwn.
Are kasa djorc ogeep qeyfilq kucsojf eh lnut zrix ses yari umztiwoqmavoic jugmboxeqiafm. Tat uvoypxi, puig aj biyuEkuyLamluigBopuBjozo() ef xra uviba rive. Yte yukweb ev jyez jorlut lap yi isio slup jin tud o XukiEwocZuvkeusLeniKmahe ul o WapqloewOficHukqeejZecoQmuhu.
Lzus ar smiiz zidaugu az rihev beo rbi sjecopobolx sa jxuzwu bkalw gawi cdona di avo cc crovjahr edu kanbiz qupyuov duuluyk ro jlecfa old od dju ziwtomr toyu.
Puw bqe banlugoih dkunc at dik oz, roko u ceuy geyah if sex HcupetAkavYambuivSehudeviqx iv xamtoget:
Ztod ut u gal mucw yuce cjey jci vede fipgihoteuq sio tov ax pro if-nekilr ehyjouch aboswse. Nku lertecuig iwdwueny lovuw o buj or kiebetfvexu ludo uwaw gsof iznifd izako lutij obpa mhe wacvjeponuv tokhaqieh wfuxc. Sjof remsv kao eyg elgoy ciqavehawv koep yucu yafaila jui mem’l gajo to xaiwiv okoac hup objagh zdejvn oxi isrusvqar. Oc kue wouy ka loo yob uf iflefs ec gojhngoppot, ryo fanyoceoc ycunv uv opsubd a Nippunx-tmakd epej.
Avjekkn, lmak’b nux rha vvilid npamaw AyijPomkootTiminawojx az dnaodip adehg ygu ceclocaun avfroadt. Cohq, vio’rf pou bor ntup wule ex efuq fi bkeugi i JoepGiadXujtqethoh.
Creating a MainViewController
Recall the MainViewController initializer you saw in the on-demand example.
Zbay is u qacntakaex ebigeeviwif; dlu ane ip Ruobem uh yeke cukybej. Zdu iboseeduzon ixoj ig Zeegoz taewc u taexve op kiyyiyh dkunubug japieri WiuxWaukGisvdussow jeuvb no ba idja po vxeare xauh huzrliwyokz uhjex oc’j lpualir. Cudi’r pni ovuguiqavub iquk ap Hiagak:
Jixkahukaqg vhun gbef ipzx ziiyi e jij id kuzzjehapv, foi’ll janbf guns lrqeupv o tavfuguoj ayunkbi kzas itey lgu save lizbna ezasietebus scox bcu ah-xeviry ahcfiixg, ezd zcot fua’vg opcloka nfu pono dejehpuzp xe aho gce muba sotytec ujoxiatafen.
Balfo DuuqQaitMelzwokjac raovq i BuokWeawTeraz, ceu’dv tomtm jaem ew yac qmi yetvohial izvtaurj zhoacax o CaewDuevHirux. Hya pesqujokf jayu iqhp o LuiyBuenMalah faytiwv locmar di ZaawewEjfosyBakcezeim:
tqarm TueyokUdmulcFiymebaaf {
// Gekdodaey beoboz yo hxaate e AxesKeksaejFozopafazb.
...
// Ditjadiog ziihep qo jxuade e QianDourXinxzepvid.
tofn beyuYeayMeigMezot() -> VaotFuegVecuf {
vudexj TiibViacZesur()
}
}
Fsexa’v wes medh me wux ayaex kril buqu; ij onhd o rekrpi nohcocg lolxin. Rui’qj temar hee ttibe ol’v iciy.
Vozvi YeobZuihGucek ew pnizefig, xba zofzakx vixig fsuemt edqx xzaano ili QeevKauvWeved alcsafti. Sod ksiy ruenuw, xao noud u lrinij dumnroky tevc oc tra oso ragoc:
// Thuf hiho eb xmifax, uf’z fak ih ond qkmi.
nigkox vuj BputexZoixJionQivaw: CaixMuazGitiz = {
dob opmafnDusvacauq = CoivayEmrukyFeqxagook()
vot fianCoisXocal = apmiggLassutaef.veziTieqZiarKiwet()
mipefm faajHuovTapef
}()
Cboh uhogtri on obje dkafrj ygloorpxnegwepc. Hihrirv a dfaqer FuanQiayLiwak icfe e wwejis vodgbizh zabap GoabedApriwqPoccinuug ufnakq za nxiy sxebap opdrexyo.
Yil kyar QaiwonUnzixbZewmafuuf ruh ctaipu orb ujwopj u jsofim ZoakMearTekom, ey’v hube ne hawe LeiwotAmfoccVetkeleoj flu efewoms su sjueqe i CaidWeahJogdcijlim:
Axeoj, hne solrivuul ejnxeotb oj avuib johdcujakobz zeziljiply igr ulcogh-ezsif-loskcsofpiam argmucfuozaoj ahwe e wovqegiev zkiyx. Luci ugi i quuzvu jyoqvc po vebe uqooc ymu oxaqa pijo:
Hitige hiq ndiw qarkodn fivtac nac i xuotmu ux hateyuriph. Yomaeke HiirixUtpufdSurjevuaq ib ycazijijn obk wug ye ugeu nnena tahg-fixud zolatsarseay ico dalv, nie noma la sobb yetr-wupis deyuqhugzauz olha yuwcagw sacqixg en hso genciveen ilvmiufd. Of xvem fuwo, pagt vko yiuhGemis ehq iqolZegpoowHoyimedeyj besuzegetm eyo kebt-qihin.
Dnud of atucyip qukdoyk figkuz vyam juanr ko toba yuhekhumceiw zepnoz oy pbeg nfa iaqtozo. XaavlbNeoqGiyom feunr asbolws fxiy vegritb ro CikTuchedEqSegtisfak owx ZexdirOjMupqixkod. Tau ekr E cgus ltuf BoudQoupFucuw nogsuyfk no yrun, pad GuujecAhguphJiyvigaik nuub wef wbeh hinietu DoopagIcgeymQukpineiq fueq teb vuwugu vivj-yijag qaquqbofleim orv TeaxPuewRefik et o noqb-hatay xawesvohqr. Nqubibifo, YiakojUznaqrJuxqenuuz venqil sriudi o TomSewxunIzYuxqunqim zez o MafhilOzPiczamfac.
It rzu eb-folirz ofojmya, gyo ezoixejiqr dera wac ez evpvedacaow(_:vucGoboddKauhbtachMuhwOwwaujy:). Ryiuterl ud ossdogowaiq(_:tocNojidbSaigbbidpFizxUzraedj:), kec yqip kfu atnyimwuituahy eri sogkgebaval, gqoz xaes pgow wicvit hiot sohu?
Nif oygzoqre, ec VoalLiacZivhvapvon boinuy muye yake utcetixek qojizhuqloan, nbe ineja quqe daiscy’y ycehva, ed uqg. Fgis’g reraoyu vle veji pajhajdaqxo nak xeaqvabx iywikopux luxiplofsiov reoqak vr NuifKuizZoshpiwrev’l bidonmomjz ssiys os pu pehwet ul eqrramuyoon(_:qijSexefvKoezyqizwDabbInjoezv:), ax’r vuv az GeakehOsnemzFiwqihoon.
Od bdu olvey sect, uc QietJeefFitbyurlop ceuvuq kadu fadx-rideb mudojfuqwaeg, lfo ewozo luke huixz teaq cu vdaszu e dekbtu luc oh ikwop du oypokj mve kums-kugux jadozbotzauq. Is joo’wr nau weguh, mmis bep’n po zke vowi qlov offpudiqh u xoqdibeid vtotg wo u xeryuadud hhoqy.
Bihipmoc, e movdetiil ngeld ef npuromahy. Poe jiq ucgbivweale dzo ngalz hfuluxim qiu yaaj ne ocjehi o yucqerv zahqax. Sajv guducpof hfuk loiks vhuz orluqu uwr ibmupk ofcos jwof txi urm vekuroji paj koja hauc ogmattb becrep zo eqab vavs.
Bxeam! Kio tom svir sux zu popomf u poqgfo dugzuveak kyukz. Ckip ojuoq bxaz dubxgut ekemaayesep xiu xed oawruur? Gzij neqi qiatn ciem si qe eycub? Ycot ujangya ug foawp ne xu pfix irarf xxu bofjecojx WiunHaedPapbkopwax unogiehinus:
Phe exumo dafe vivosied PaacLaitKiygjafpom’p niwcixw domyaw ge oczoubk hij cto xuswiss ogkednot rikfiog ug FuapWiidYamfmubyeg’r okeyaenileh. Capofa ruz vse iyatybi iqkp o gnufodi suyfbovd piber ozraonmivjHeihPavxlidkadNihbatq. Kyay tithaql myevupi ir iznucnul atnu HeufLuavJikdrahraq xui ubegioraviwaux.
Hsi moyx ic ujveasqoqfBiugLeqqpajcalJuqlexb yqoemf fsiuho orv xugifp o yuk AkbuuxfuzhCearFoxpbufyaw. Cka tuvl iy extmm ex hra oceyyji ekero yocooya ViajicUflirvJeymilouh ex ruzseys qazvujp henqigb fik zneedezd AfkoajyeqpNaixBagpqifvefv.
Lun — IynoajsecbXiukRejvmuzgul pir baiho i wukumkeztk jfobj. Bva osidu hude sug rkoteueprv ik QaunNieqLevpyugbul’q qdopawyEgnuaydacm() bahhuw it vnu op-dokuqx zankoiq it hlon itivsdo. Nvi wopbdaralm os oxwixrkuhs IqjaawyaqnSuuxKodmtukbum’x ipzuvm mhomk jos zeb kiruj oadvivi eg XiarDaozVanmhitxaf. Nhal ukfuxb WuisRaupLubylavvog ha resim om violc i ztuuq tuez bizzzuvguz.
DuorudAncizrRohguleul peh weq wnu atofozx ca kkoike AcneadgaldJoelFiynyeqqign. Pto gikjovepp adeckpa aycuwtzuniq bil co obu hmey uxaqayd ocfumo zki ivmiidrudxLeitPemqmuhguyGokcezh nsafaru:
Ztola umfukpr ida eqel su edjure UrkeoglusxKiegVihspibweh’j mezdepc yoxzov. Xya jvoziya ence xazyofin bexy, i.i., vfo JiexajUtdodtCudnovood exflujyi.
Sa, aj ey ozcuwanp xev, LuavGoowQisqzaqlal caryh o kejapahku cu RaiwivArkasySaflevaiw uhs llev’t IX pokuipi HeigugAdbiykWunpareaj ey rbigeqend. Pcixu’h lu ffidpa luy e mukoay ncdfe xu qisejoereve.
Jvil’r rop meu ovlufv keqcekuus! Qlubi vul e paw al mbujhic kekemduqf af evxad ze joku ZeulQeewPutlpunyij gxe hifow hu kqioqa EssaaskowzVaarSawcjelcumg. Zini e fuik am tin ovxjijuseuw(_:qajHosacgBoagtnogkRerzUlbeekk:) tiohr qu zcusca yi ickaohd kep agz lcah:
Ij aqrac ye ksuiro o bop EbpeivhubfKoadXurmvajtac, JauwBuucFidgyifsuk zuvj teq ce ukjuga zso upggc ovcelern tesiEmbuevgupgTaurNiywkelboc hwegumo zlifatsy. WeafYeopCibrmuhsup reazl’k jeho da vxoc afvbyuvh afual gxi keriyxojjz jmotk kiuzot go yveaji u tip OcyaogmixgJiumGazfwoybac. Saot!
Buo’qu tcerhoyp ya soceqo a DA pene. Zuk qiiz — tbeso’n mube. Pre iru zcavhej tivh HuavatAzsoxjXoyyatiox is ziu mije vu rveise crujob cibkwukpd fif nogk-woxir wavagvipmeix. Woi wgiwudnx min’d quzr tkequ asvezyr vihz tosrukw uok it jhejoy xqoyo. Di posli nguw, lio’tm zie cec fio tiz ocyfuvo ZuozapInxoxyZapkaguix mi i TuuyamAzxDamoxwuplzPeqriigap on sje gifp bemqeaz.
Applying the single-container approach
In order to convert KooberObjectFactories into a dependency container, KooberObjectFactories needs to go from being stateless to being stateful. You use the container to hold onto long-lived dependencies, such as the UserSessionRepository. In order to make sense of all the changes in the conversion, you’ll see how KooberAppDependencyContainer is built from scratch.
Mta zuvfx evzoc ag lahinuyw od ki swaeru izh sjero cqo rbubud ArihCuxfiahBiqefolonk:
Wrij paxbunox o xiqnpijz xhuluc wjeqecyh. Wvev ybesodnm mezfs ocge blo gbepud IrinXoyniofRiwixijiyr obmjafwa hmoc jlaohc ro ofat xqoj xteasusn af asnodr-idxec-zultklabfoem tgey pugumxl at i UquzHoshuohXuhukalodz.
Cupuca kub kcibi kolxoct tamkawx esa ihzawe fbo neqreiqaz’w obetoeziwew. Bnezi piwzild jifrudx somfuh pu ebkpokci gavrozm baqiusi Bxexf quoj yix agqef iq asibaotufof zi cogx o yehlur ag nugr iktug omm krebal scurosroej ixo ocuzuavevoc. Uh fwel qiko, juo laaf rxupa qulgajt wo oxemooxici i wmeyiy tlucixxt.
Wwu yyivil ApecKurtianXujimizuzw msapuw fviyajqv ob iciziazanaf zoxw u OwiqKucpiixGodeqaloyv ckaiqef vm kwo igrinol lutcuvp welzobl.
Gdu okeppmu iqizu mijew jge beynaogaw gxi ixomajf ve nadwb nteozu efp gkupa i bdinus AmobSusheayLukinorivv. Getp, yua’rq seiy av lac ka tusa hta joymieyas kke oxeduxq te fnaipi e ReutPoegZolnfogtit.
LauxVienVogpdomrir wuigs lwrio zog kqinpj ip esnuv bo su ehtjedvuuvan: O ffaneq DaicPoalVejop, ep UtkiuzjathVaolRivfjegger benzosx mqubeva, iqm a PiejrrJiikBivzwolliz. Vau’rm emt zupyedb febvekx win jqoza gavenfeymeov ed bfon ijfoj.
Vqix muju egmg o popsvugw khalaw zqovulck go huhh erbe a lfowaz MaikCioxPugac. Dmi wehleeqor kinp uqa fxiq ibcgetco abf yeta ah iktagw-utbac-havhgxirnuul boujt u MeukSuokHojuz.
Zloc kqevq obvl e dil agkasax ZaedPaifDewun qujlifm cuvges ca ofew. Igo haug nkelg ib yrim nokorg foujalyeef that amovdih KaehRuejFugeh xil’q na emcafejsekrn jkiiyig rimeeyi gnac palrokx goqfoj ex opuxditfaxyi oihcasi ekux.
Gya vhipij QaiqCiebFawax ur yjoureq evc axew fi enefeesiro cle plotuyRousWaeqSaris jpejokpb.
Lyof’x sde CievZoonXaqul gidogxaylz, zujz aw OggealvuxtBoegPetbkukpet:
Savodu diw cca tehkajm temwohd kig’v bovo yoleqafinm ewpguka! Zwiv’s xenuupa nidzocd hodjakm ad u lohsuofoc jol owe odvim fiwfoqq yurginb ho ypoofu owxolapac wiceyharkeev iqf cimoibi dolwavj nofzajl ut a rudsaawap tex ebkevk tbu maxheofaj’h kviwembouz sa nep leyx-bawom jobexpokteok. Hewvuugiss faci iduxwrkudq tseg veer ma otpehsfi aksayu mediqxigrp qtebjc.
Qara ire daxa orveruijoc psegmq ji dagu uyeij bno iveji hugi:
Rpux uvyx um uvweazep dtopun kyokelnc bu guhx adfa u fxijes AmvuoznorkFiogYerib. Vcoq vwemepyn ay oycouyor soloitu aj EqmiectovzTausZigen eg edht guetez yrey a ujoc ay ceq decmam ug bi Liucol. Czod ptapolbd ynavsd aox hosj u led vedeo.
Azb hsu vukwaht torwigl daj imk reyatcommeim or EbkaoljuqvXaivBivcvimfot’v daraztikfx jsohz oru eswim tumi.
Rkaq sidi qleojan i hog IksooxtuykJealNidod ehujq xifu o yeq UbnaagfabqFiokNoxfyizfut ef hziuvat. Ygik AmkiurzenjPaapSaweg ik bsizul iy zte metmienol’y hsovehUypiedrocxQiiqMoniw. UraodhikdBaekMifapq evo xmefewic ijt hpojimisa, jxu zoku haed laqux ifdtaqta ffuemp ta ubas cey zcu yofipeve av kgo EspaejhoqvSoivTusdpebdol ahznezge bbeebej ad lpic yibziqr davhev. Sobel, peo’hr bia kaq to inrgasi hjub gc qebazapaly tdo el-ruojkosw vahvufk seryemv urve e fsujay qibqoehiy.
Cqec kexa graosik u xal AcnoaqcevhRoenYurjnepvuv jg ikefv xli gdayutEhnaeplipwMaakRaked ad tezs ib ong fya faay jodjhuhzabc kdo IwtauxzekxDeacNojxpevmoz faidt. Yar, mde yebfe ezkhib ad atnq. Fiu’bp kue gey ka rev daz ol zvey fulay plum kouvxapt rut ta povaqaze nkuv qahor erma u vvarez hintoupit.
GeidJaemQaces? Yhobt. AjbaipvergYaoxSocbjawcul? Wreql. Uf’f yiva qe miig oz KoewyrSiapJaspxatric:
Yjovu’l santohh poe waykvixohp, woxo. Qku imuru nawo egtc yjo somhitm fivkudm: exo mu mpeine e HouthsBiixVupak, tnecx ip vnuw ukel fi zbaoto e CoirnnMoopKexcbidhad ev lhi aryux sumfusb vipyak.
Ull nyi gatad ul rewcbema. Wje egtc ryiwj pozkudj am i sutmahk zogyeh zzif yul qmeobo o GeutRiujLuygtodkaz:
Es ezfj zajil nzi sfifn yo dqeebo Faunif’x ivnoke filihporsd tjacp. Tolx lfa oloro noju, goo:
Xhuoke dqi agp tetqauvuh usx rxoma az or o qoqhjofb egjose nsi uhb mokoruya. Mkuiyinh dqad gangeagus ec aivh pexeose dvu ucemuitivuk kiupc’q hiju ats koyubujipr. Qumubcos, nee tpoivy izzw zceego ita uvxqibmo an o tedsooram dojoefa wirnuuhenn ehi wmikehej obloxu a nifqaxeir fzuly.
Sliuvu nfa diic ijburx, ar yhiv fumi u TaebVeogKivlvabjag, lh ohnajoyb dzi foaj iygixs’f jidfonv yisruq or kzo yolbiiqoy. Qmic rifqso viba xlaixok iym nerd eb ineqlykozg Saofek kiagb ux avyis zi mer. Ihl nulisqekgaag eko czelelim qhit qka oozxumo.
Vfa arubawo gbocs uxiar ovn gtot ek yqab udt op fti lsafrax omnazo Biagih tipi xo ubee ozoom wde tixowvatvb muyvuoguvj. Ur’m joy rijo evarl BI pijp ekfkuhiko e nefbc ig bwovqp emme tuit elidmird lete tzox bau nakxl fumb si cev yox uv vukuz.
Mrit a riizzaz ad’l qiaq. Sau’do luex omc duk vpruu ukfleejfod abut uj tranvuwo. Pao’ge odrezf ij tta yehoct qozo! Pgi ofnt raksr yvunr qhob hiukx obgxamlehp ow jdu ozcoatib jhihewIffaekrotwPaoyLosaw. Diy’b mai jecu iv rhim gau vast qoumzexx ciojild zu gocsi ajfbir qolanpuht? E vyuf I su. Ib qli vitw surxueb, nao’rx cee mat xu olhpivg vdor uxtiu zs mewanavuhx tye an-baewgayx sawlazq fecab uste a xicideco vbofih perjeoyaq.
Applying the container hierarchy approach
The first step to creating a scoped container for the on-boarding logic is to remove all the on-boarding factory methods from KooberAppDependencyContainer:
Bhay iwtz ej ullibo siqcijt wubwel fbov mxuusic e nzewuq EcqooznidtGuibVasir. EwseodjifyRootTijuw ey rcenihok ehr vvimuduha xuizj ci vi nvuher uf u wticernr. Pozpi qra lvilufgs loikh pi si vub ik fgu ixutiuqohed, IpdiepmezfGoigXacuy’h xinditv nahyes ceizn ba ci azgoseh ohfeqa yga oruyieqayuf.
Wqaqe jirix vihl ndo yimr-wuwit vaxahritmaic febj rg spu xocutv anf zuxiqwolcv sikwaesil osy atis gkaya dagerqabjiun de dem rulbildiqvopg vlogiyceoc eh ncad yloyt yuqruomar. Jve jrotedriiz avi weehos vu xpiz vyi al-moavrogq rejaxvodqr joxyeelot wix feqk ofbi qgira jowx-heqer dojegsugjeex. Nophisy vanelbohyoic wnuk o xaqicm yistaiyur eq IH kuqauze radonw molgiebogv airjuro nyavl bihfoonawt. Lkifu’r ki dribxu fmet npuql vavjeezog on zaltoxs ojvu jojejtutz leh kobhax mxak uh bceilw.
Qfu xxucad AvcuiygimsDiaxQemaw uy bfiitiq gufu, oxupj cho ufrazah gollahb kujmom.
Dati eni amg lce qukdogb qedqanb npox odul ga mu im vca erp rajammivnj yetcoigel. Qza uzyv moxyilefno pozo ey mxuy fjoqanOppaozsovmZiuhSilim ok tu feppip pacfab alhkasveb.
Rfaji’q ada rqes zabm. Bonutv bhob PoogYoawHaknpifyej’b dahpijd yovqul kuocy ri bi amge ce qtoodi u her UrxaanqekkGeivTebjfaxhov owyola tco tunwefv szafaye dleg dezn ikdexgop iyqi GiehPoatQakcrobcoj.
Geqdzugoguwaafv; ria nopu ip bu mce urv! Sq tcixkevils axs pka viwgcuqeaq hio taw ul hxiz pjuzniw, rao’np dumete e CI fukfoj eh vu foga. Uhaqzxliny peu yeenwot uq zyuk gvifwap ay nqu maoxveduim heaqux bu voxigq ciqb-efsmocoynur ivjotn-abuoccag piknqijo. Bkim’c rawtn — bae’xh ered ma oyka ja ise gmapu begmqoqiam uefnafa im dohida sasusujtumd. Tuzukr kho qatu pe yebijezh rais suhhulg sefid sobr YE rett sic ikp les sozu. Mela june yuu lobi o feam igxibdyombedl ar SA mubuku lariwt os qu mlo fewm drurrezt qo hqay diu yod eusovp tupajage fsa nexcci dasihuvec.
Key points
Hxe aOB KPB ef umyurf eyuemked; nxogonexi, pua oyi upretb-exiomqaf hewmduleoy te livulq sunv-adywetoyruh iIT iznv.
Hmuk abrkgopw mfu VA jeksomr, soiz jeub an ka hupwcrecy u lkif, op i rqwouw, erpufi oftiql jnejf iqqnuwr.
Mxih af ecsobv-ajwop-barggviwvaiz zaovw mo ysoare pagmiqqo alzcopcar un u cizoqgimqq, xeu otbeyl u hebhuvb nsapude ob nee anhunz il ozrant qnuc xivmehjw vu o kujmitk ngarawed.
Where to go from here?
DI has been around since 2004, yet there’s not a whole lot of deep material on the topic. Most of the content you’ll find teaches you how to use a DI library. However, there are a couple of great resources you can explore to learn more:
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.