1 / 23

European Conference: Dependency Injection - How to Decouple Your Code Modules

Learn about the concept of dependency injection and how it can help decouple your code modules for better flexibility, testability, and maintainability. Explore SOLID principles and the benefits of dependency inversion. Find reading suggestions and discover the advantages of using a DI container.

marionn
Download Presentation

European Conference: Dependency Injection - How to Decouple Your Code Modules

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. europeanconference

  2. Dependency injection Howtodecoupleyour code modules

  3. What is dependency injection? • “Put appropriate instances in; don’t let the object create them.” • Thanks for your atten… wait, wait, its “a bit” more complicated…

  4. Whatis SOLID? • S - Single responsibility principle (SRP) • O - Open/closed principle (OCP) • L - Liskov substitution principle (LSP) • I - Interface segregation principle (ISP) • D - Dependency inversion principle (DIP)

  5. Single responsibility principle A class should only have one responsibility • having problems finding a name is a sign of a violation • creating things is a responsibility -> factory • related to separation of concerns (SoC)

  6. Dependency inversion principle Abstractions should not depend on details. Details should depend on abstractions • "Code against interfaces (i.e. abstractions) not implementations (details)"

  7. Whatisdependencyinjection "Dependency Injection is a 25-dollar term for a 5-cent concept." "Don't look for things - ask for them!" (MiskoHevery)

  8. Why Dependency Injection? • Decoupling of software pieces (classes) • SRP • flexibility • composability • exchangeability • testability (mocking) • maintainability

  9. „Tocreateor not tocreate“ • Injectables and creatables – whoiswho? • Exampleforcreatables: • All kindsofcollectionstostoredataorinnerstate(lists, dictionaries, TStrings, dynamicarrays, TStream) • PODOs (aka dataobjects) – but sometimes not directly but with a factorydepending on otherrequirements • Injectablesarethosethingsthatactually do somethingoftencalledservices

  10. Reading suggestions

  11. More material • Not onlypurely on dependencyinjection but in generalusefulthingsaboutsoftware design and architecture • https://blog.ploeh.dk (Blog of Mark Seemann) • http://misko.hevery.com/code-reviewers-guide/(Guide towritetestable code) • https://www.youtube.com/playlist?list=PL693EFD059797C21E (Google Clean Code Talks)

  12. Pure DI • Learn and understandhow DI works, whatpatterns and practicesarehelpfulbeforeusing an automatedway • Try puttingyourdependenciestogethermanuallytoget a feelingforhowto design yourclasses and interfaces • Onceyou‘vewrittenpages and pagesofconstructorcalls, considerusing a DI container

  13. Service Locator • DI isaboutpassingthings (totheconstructorbasically) • Service Locator isaboutlookingforthingsactively • Code smell and dangerous anti-pattern • Createsdependencies not only on theservicelocator but implicitly on typesthatneedtobeexisting in theservicelocator • Not easilynoticablewhencreating a class but onlywhensomemethodgetscalled

  14. Composition root • The pointwhere DI starts – ideallythereisonlyone and it‘s at theverystartoftheapplication • Whentryingto fit DI into an existingapplicationyoumighthave multiple at first • Move themclosertothestartoftheapplication and eventuallythey will converge

  15. DI Container (finally!...) • Factory pattern on steroids • And a repository, and someother design patterns • A centralplacetoregister all yourinjectables and letthembecreated and composedautomatically

  16. Registeringtypes • RegisterType • Tell thecontainerwhatimplementing type isavailable and aswhat type itcanresolveit • Possibilitytodelegatethecreationtoanotherplacethanthecontaineritself • RegisterInstance • Tell thecontainerabout an existinginstancetoletitparticipate in dependencyinjection

  17. Registeringtypes (advanced) • RegisterFactory • Register a type and letthecontainerprovideitsimplementionwhichthenservesasfactorytoreturninstancesreturnedbythecontainer • RegisterDecorator • Register a type and letthecontaineruseitasdecoratorforotherclasseswhenitresolvesthem and automaticallyapplythem

  18. Controlling lifetimes • New instanceevery time oruseonlyone? • Transient vs Singleton • Possibilitytocontrolwhennewinstancesarebeingcreatedoralreadycreatedonesarereturned • Singleton, SingletonPerThread, PerResolve, Pooled

  19. Type providers • Possibilitytoextendthecontainertogiveitspecialknowledgeaboutspecifictypes and howtobuildthem • Examplesofbuilt-in providersare: LazyProvider, ListProvider, DynamicArrayProvider

  20. Typesofinjection • Constructor Injection • constructor parameters • mandatory dependencies • Property Injection • properties/setter • optional dependencies • Null-Object pattern • Field Injection • Use only in exceptional cases – this is not possible with pure DI

  21. Controlling thecomposition • Typescanbenamed • All injectiontargetscanbemarkedwiththe [Inject] attributetocontrolwhere and whatisbeinginjected • Additional conditionscanbeappliedtotypes and injectiontargets (planned)

  22. Let‘stake a look at someexample

  23. Container.Free

More Related