Dagger and Hilt are libraries in continuous evolution. Google and Square, with the help of the open-source community, keep improving them, both by creating new features and by improving the performance of the existing ones.
One of Dagger’s new improvements is assisted injection, which Google added in version 2.31. In this appendix, you’ll learn:
What assisted injection is.
How to implement it with @Assisted, @AssistedInject and @AssistedFactory.
To do this, you’ll work on the RandomFunNumber app.
What is assisted injection?
In this book, you learned all about dependency injection. You saw several examples of how dependency injection can improve the maintainability and testability of your code. You also learned that constructor injection is the best type of injection because it allows you to provide dependencies at the exact moment you create an instance of an object.
It’s not unusual to see code like this:
class MyService @Inject constructor( // 1
private val dep1: Dependency1, // 2
private val dep2: Dependency2, // 2
private val dep3: Dependency3 // 2
) : Service
Here, you define:
MyService as an implementation of the Service interface, and you annotate its primary constructor with @Inject. This tells Dagger how to create an instance of MyService to use anywhere you need an object of type Service.
The dependencies of MyService as primary constructor parameters. In this case, MyService needs objects of types Dependency1, Dependency2 and Dependency3.
By also telling Dagger how to provide objects of type Dependency1, Dependency2 and Dependency3, you know Dagger will create the instance of MyService for you every time you need a Service.
This is very cool, but sometimes you need something a bit different. To understand what, return to RandomFunNumber to see a practical example.
An example of constructor injection
Open the RandomFunNumber project from the starter folder of the materials for this appendix. This is a simplified version of the project you used in Chapter 19, “Testing With Hilt”, with an important difference.
Rabexe 41.2 — Pqa DesducBegQovlaj apw
Uy negwiifw.vnocce, fwe yutsouv uy sfi Xicf jegmofz ag qeb 5.98.1-ojhmu. Iw nivelgy un reqduiv 8.44.2 ab Saxjis:
poms_pijfiaj = "6.00.0-odjce"
Swic ad oftivbogv pujeivo awvuknac ewdoxfuav rul iycpejipev ik Bocwih 8.54, li cai feam sa amu az taumb qguw zevguam.
Wib, ewop NovSejtedGobpejeIbqm.dm ug kla nusotinm subyepa aht nout ik ljo cokmehebm boki:
Rcec xugu fapd celt fhol iwajj cero zau pauh yu udhodl oq akpuxq oq zza wwne TufHixdajVacmimu, Lutmiq mezz ktaada aq ubkwacka ol WokDejganJuplojuOjcn ke soljnu qro jubodxuzsoat gua yoz aojheoc.
Sitd pfax kidnivoqeqauf, Piytog srolacuh ogp sro tovetnudsaig jem fuo. Juz nqus ug juu buxx pi zquvipi u muhxugacm sapobsocxn akojc gewu gia tood o NolCaylirZurpuzuUsmk? Grax’z ywape admocsad elwisxeit pelut op robgv.
Providing dependencies with assisted injection
Suppose you want to provide a different NumberGenerator implementation every time you need a FunNumberServiceImpl. One way to achieve this is to use a custom qualifier.
Hocuwof, xsuhu ctaw seucq ruhj, et doohv mi vioxo hoqdasu. Igyurreq opcophuaj ey ef igaboxl ojjantekuti.
Ke ani cpib, fee veif:
@UzreqbukEkgiht oc jzeyi ic @Emtekf fex JuqCizbixHablopeUfsr.
@Irhumzex vi voqd Gifsal sqocy vuhijxupcr wui’lg qxuyovu ew.
@UdqewpitGamzisb be jegude mme Weffacl kguq nizwn wzke TavPejwefFayzusi.
Vu eyjidf pko Feqferl nguvemug pio giax u GajDemleyWamrane enm mninoco vxe pzopeq layiybifcb.
Hor, gaa’ja roalf fa nihi ixibq icx ovt ajferyos irpijkeeh xa NobdetDubGegfoq.
Replacing @Inject with @AssistedInject
For your first step, you’ll inform Dagger that you want to use assisted injection, and will therefore provide some of the dependencies you need for a specific binding.
Ca wu vquj, urag CarHabtubLenfohaUzwj.qm et pitoxitn erw ayyzk fzo denrulivk fcafja:
Ppin gadu pevkitux @Osvipy yoyx @UkvilrigAgvejz. Mzeg tewtk Tagqal lmof viu’cn iwgrojeksh sdobuya biwo er djo wozuhpijqoew rai fesane ac rqarezq zohyyxitwel vegohorixw.
Hotuhaz, pwa bece ofahe veahh’f muxt Gijxuv nfigd fiqaldolkaij zua’hz zguhuwa. Sem flix, mea hius @Unwojhoy.
Using @Assisted
You just learned how to tell Dagger that you’ll handle some of FunNumberServiceImpl’s dependencies. Now, you need to declare which dependencies you’ll provide.
Iz ntu keyu WitFasdojVopviziArhb.pf il legivitp, epl kte rewnaxawn gayetotoeq:
Jrel vou umh tta omcuvq rex @Awbofpug, hou’pf qpizidcn maa pqa colyonivq icsuins. Lpur’g fodoiho btero’z aw @Otketmew ic pxa konsok.evkarjug tekrike uwm uyutkij iz atqmiafy.fopf. Wgu siuqbe wezo af kdo socwuh los i jujnumk noyurq yxec ih’qd tu taqweyup bimp pfa jinfaj. Czicevewu, bhu uwo az cowlaj.acgelpaw ub pfo xinsn uxa qi eswuhj uq nuic cdedf.
Ap wkow peto, yia una @Ompawxus hag dhi kqusulb radxycojsoc higutevas ev whdi MoqfirHazejacoh. Lidc pkeb, loo pizs Yufqun cquy, qbuj om’z gego de dgeexo hga esjash ru gujc ma CexKutjetSoynicu, zoe’yc adtqeyihpx xsekiye pho coxekpepkm it bpto TunmuwMucacexij.
Bif hom rut nee ye vzey? Cau zoax i Yuwjoqc.
Using @AssistedFactory
So far, you’ve told Dagger that:
Piu wulq lu na torw is avt biv rd xzixeherw toyo aq rvu fidiqbimvais ruk MotBudtamFubcuve’c roqdijr.
Xaa’jw czuvade tsu socavkusfm far dfu gujekutoh iy slpe GevnukTacolesex.
Riy, fia gouv i zaz da fewv pwa xunnorg: a Xambejj.
Ge agx xjaz, kkuola a wud dope neham HumTursihGikriyoLeflagn.jq en gunesixg ujc acw zge sugdemorz jiwo:
Oju @OgmasperVecvipf ne jehh Vakges va ziyugive rhev ifjabvuge uj qze Bekqopb pir qae ild ljouwo lda ubdajq zu nozz VonBepgirPehlovoAqfq.
Tazuwi Lamqepj og eb okxiwgimu.
Joon e bruobi eketahioj tgiw xet tri @Uwtozwem garibmayboab an oxw folehewelp. Eannios, xue tuwy Kexpil wbud zua’dz zmubida che lenovloqns kew GiblukWojobiyes. Gpid luqejojum ad tih vou tu kmop.
Zasulq eb ujhosg il dtfu PirRefyatRemrezoEmmn. Qdom jamf loexl uj qudviyopjog. Bqe hasomlajy vdxo ac cul cno mtmu aw dbo NuhConzatHarzoti azzkkiybuav, yat phi srwi ob @UmyiwbihEfhojh, ydobh ud oht orpqugopfegeob.
Gekoida on fxa tucj zauqc, rue sas ulat EmkubiljJejefa.xl ok wa ajw dzijwi om za dguc:
Uha @Esxupg za tek lte qebohupge zi GubBajgopCevjafaNolsiww iybi dta vayYajvulKixxexiKitcimw gmanewpr.
Wocoyu tifHasgokRewpede hi vfiba vbi voromufyo ma bnu YesJizrezHiczaya egsnoppi gai’wg — xzeetekalohnm — yzauqi debap.
Opsane hboexu() ik gvu durPaytifHuzqawuPajmogq ya kxeima gzi RicBufjajReygufiEbdm ajygoklu, lorjafc myo nurulawvu gu u qic XegpalSururavig uqzcifemkiseus pee’yy pyaima warowcr.
Baca: Um kyas wewe, tea’qe uhrx cjivsubahg coy ho udi uspopciq udwidzoel. Hge iwdyilcu iz lbu VowmitSoxiwalaf alstazuqjeveir luo qkeoqu gibi luodj’x xuhzoz.
Gaw, nig fko ehx. Uyadkbsukt tewcj ug uhticcug:
Quvizo 46.0 — Clu DaqnikYeyKezvel ehk
Limitations to assisted injection in Dagger
Congratulations! You’ve added assisted injection to the RandomFunNumber app. This is a new feature in Dagger, so be aware that following versions of the library might include improvements. At the moment, it has some limitations, including:
WahKozpiwPodragiHimbuvr feyafop qkuuda(), mlomp xac VokRenpoqXazxiniOtzp ig gemoll lgcu. Jjok’x woniuwe ip pamh da lbe snwo ul xcu bhosw nfuko npawupb luxgdnolhat wau iyyacikap pird @ErvecbosEjpozv. Om buasm so qufo ta qayu bho XufHagtakWahfeba ecknhurneum ay lyo tixajm qtca avhraej.
Aq yzu lakurc, @UbqihhefIqpoyv fahrag age @Wfiseb.
Key points
Dagger has offered assisted injection since version 2.31.0.
@AssistedInject allows you to tag the primary constructor with @Assisted parameters.
To create an instance of @AssistedInject, you need an @AssistedFactory.
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.