230 likes | 244 Views
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.
E N D
Dependency injection Howtodecoupleyour code modules
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…
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)
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)
Dependency inversion principle Abstractions should not depend on details. Details should depend on abstractions • "Code against interfaces (i.e. abstractions) not implementations (details)"
Whatisdependencyinjection "Dependency Injection is a 25-dollar term for a 5-cent concept." "Don't look for things - ask for them!" (MiskoHevery)
Why Dependency Injection? • Decoupling of software pieces (classes) • SRP • flexibility • composability • exchangeability • testability (mocking) • maintainability
„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
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)
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
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
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
DI Container (finally!...) • Factory pattern on steroids • And a repository, and someother design patterns • A centralplacetoregister all yourinjectables and letthembecreated and composedautomatically
Registeringtypes • RegisterType • Tell thecontainerwhatimplementing type isavailable and aswhat type itcanresolveit • Possibilitytodelegatethecreationtoanotherplacethanthecontaineritself • RegisterInstance • Tell thecontainerabout an existinginstancetoletitparticipate in dependencyinjection
Registeringtypes (advanced) • RegisterFactory • Register a type and letthecontainerprovideitsimplementionwhichthenservesasfactorytoreturninstancesreturnedbythecontainer • RegisterDecorator • Register a type and letthecontaineruseitasdecoratorforotherclasseswhenitresolvesthem and automaticallyapplythem
Controlling lifetimes • New instanceevery time oruseonlyone? • Transient vs Singleton • Possibilitytocontrolwhennewinstancesarebeingcreatedoralreadycreatedonesarereturned • Singleton, SingletonPerThread, PerResolve, Pooled
Type providers • Possibilitytoextendthecontainertogiveitspecialknowledgeaboutspecifictypes and howtobuildthem • Examplesofbuilt-in providersare: LazyProvider, ListProvider, DynamicArrayProvider
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
Controlling thecomposition • Typescanbenamed • All injectiontargetscanbemarkedwiththe [Inject] attributetocontrolwhere and whatisbeinginjected • Additional conditionscanbeappliedtotypes and injectiontargets (planned)