Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp

486 views
400 views

Published on

We will dive into the basics of Inversion of Control (IOC) and Dependency Injection (DI) to review different ways of achieving decoupling, using and exploring both: Best Practices, Design and Anti Patterns. This presentation requires knowledge and understanding of basics like DRY, SoC, SRP, SOLID etc. which are building the base for decoupled architecture.
However, we will start at the basics of DI and will work towards intermediate and advanced scenarios depending on the participating group.

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
486
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
10
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp

  1. 1. Silicon Valley Code CampCut your Dependencies Dependency Injection Foothill College, October 6th 2012
  2. 2. Theo Jungeblut• Senior Software Developer at AppDynamics in San Francisco• architects decoupled solutions tailored to business needs and crafts maintainable code to last• worked in healthcare and factory automation, building mission critical applications, framework & platforms for 8+ years theo@designitright.net• degree in Software Engineering and Network Communications www.designitright.net www.speakerrate.com/theoj• enjoys cycling, running and eating www. slideshare.net/theojungeblut
  3. 3. Overview• What is the issue?• What is Dependency Injection?• What are Dependencies?• What is the IoC-Container doing for you?• What, how, why?• Q&A
  4. 4. Cleanly layered Architecture
  5. 5. What is the problem?
  6. 6. What is Clean Code?
  7. 7. Clean Code is maintainable Source code must be: • readable & well structured • extensible • testable
  8. 8. Code Maintainability * Principles Patterns Containers Why? How? What? Extensibility Clean Code Tool reuse* from: Mark Seemann’s “Dependency Injection in .NET” presentation Bay.NET 05/2011
  9. 9. What isDependency Injection?
  10. 10. Without Dependency Injectionpublic class ExampleClass{ private logger logger; public ExampleClass() { this.logger = new Logger(); this.logger.Log(“Constructor call”); }}
  11. 11. Without Dependency Injectionpublic class ExampleClass{ private logger logger; public ExampleClass() { this.logger = new Logger(); this.logger.Log(“Constructor call”); }}
  12. 12. Inversion of Control –Constructor Injection http://www.martinfowler.com/articles/injection.html public class ExampleClass { private logger logger; public ExampleClass(ILogger logger) { this.logger = logger; if (logger == null) { throw new ArgumentNullException(“logger”); } this.logger.Log(“Constructor call”); } }
  13. 13. Benefits of Dependency Injection Benefit Description Late binding Services can be swapped with other services. Extensibility Code can be extended and reused in ways not explicitly planned for. Parallel Code can be developed in parallel. development Maintainability Classes with clearly defined responsibilities are easier to maintain. TESTABILITY Classes can be unit tested.* from Mark Seemann’s “Dependency Injection in .NET”, page 16
  14. 14. The Adapter Pattern from Gang of Four, “Design Patterns”
  15. 15. Inversion of Control –Setter (Property) Injection http://www.martinfowler.com/articles/injection.html // UNITY Example public class ContactManager : IContactManager { [Dependency] public IContactPersistence ContactPersistence { get { return this.contactPersistence; } set { this.contactPersistence = value; } } }
  16. 16. Property Injection+ Easy to understand- Hard to implement robust* Take if an good default exists- Limited in application otherwise
  17. 17. Method Injectionhttp://www.martinfowler.com/articles/injection.htmlpublic class ContactManager : IContactManager{ …. public bool Save (IContactPersistencecontactDatabaseService, IContact contact) { if (logger == null) { throw new ArgumentNullException(“logger”); } …. // Additional business logic executed before calling the save return contactDatabaseService.Save(contact); }}
  18. 18. Ambient Context public class ContactManager : IContactManager { …. public bool Save (….) { …. IUser currentUser = ApplicationContext.CurrentUser; …. } }* The Ambient Context object needs to have a default value if not assigned yet.
  19. 19. Ambient Context• Avoids polluting an API with Cross Cutting Concerns• Only for Cross Cutting Concerns• Limited in application otherwise
  20. 20. What areDependencies ?
  21. 21. Stable Dependency “A DEPENDENCY that can be referenced without any detrimental effects. The opposite of a VOLATILE DEPENDENCY. “* From Glossary: Mark Seemann’s “Dependency Injection in .NET”
  22. 22. Volatile Dependency “A DEPENDENCY that involves side effects that may be undesirable at times. This may include modules that don’t yet exist, or that have adverse requirements on its runtime environment. These are the DEPENDENCIES that are addressed by DI.“* From Glossary: Mark Seemann’s “Dependency Injection in .NET”
  23. 23. Lifetime a Jobfor the Container
  24. 24. “Register, Resolve, Release” “Three Calls Pattern by Krzysztof Koźmic: http://kozmic.pl/Build 1. Register Execu Clean You code Release up 2. Resolve te up
  25. 25. What the IoC-Container will do for youBuild 1. Register Clean Release up 2. Resolve up
  26. 26. Separation of Consern (SoC) probably by Edsger W. Dijkstra in 1974 • Focus on purpose of your code • Know only the contracts of theExecu You code dependencies te • No need to know implementations • No need to handle lifetime of the dependencies
  27. 27. The 3 Dimensions of DI1.Object Composition2.Object Lifetime3.Interception
  28. 28. Register - Composition Root• XML based Configuration• Code based Configuration• Convention based (Discovery)
  29. 29. ResolveResolve a single object request forexample by Consturctor Injectionby resolving the needed objectgraph for this object.
  30. 30. ReleaseRelease objects from Containerwhen not needed anymore.
  31. 31. InterceptionPublic class LoggingInterceptor : IContactManager{ public bool Save(IContact contact) { bool success; Public class ContactManager : IContactManager this. logger.Log(“Starting saving’); { public bool Save(IContact contact) success = { this.contactManager.Save(contact); …. this. logger.Log(“Starting saving’); return Result } return success; } }} * Note: strong simplification of what logically happens through interception.
  32. 32. AntiPatterns
  33. 33. Control Freakhttp://www.freakingnews.com/The-Puppet-Master-will-play-Pics-102728.asp
  34. 34. Inversion of Control –Service Locator http://www.martinfowler.com/articles/injection.html// UNITY Exampleinternal static class Program{ private static UnityContainer unityContainer; private static SingleContactManagerForm singleContactManagerForm; private static void InitializeMainForm() { singleContactManagerForm = unityContainer.Resolve<SingleContactManagerForm>(); }}
  35. 35. Inversion of Control –Service Locator http://www.martinfowler.com/articles/injection.html// UNITY Exampleinternal static class Program{ private static UnityContainer unityContainer; private static SingleContactManagerForm singleContactManagerForm; private static void InitializeMainForm() { singleContactManagerForm = unityContainer.Resolve<SingleContactManagerForm>(); }}
  36. 36. Dependency Injection Container & more• Typically support all types of Inversion of Control mechanisms • Constructor Injection • Property (Setter) Injection • Method (Interface) Injection • Service Locator•.NET based DI-Container • Unity • Castle Windsor • StructureMap Related Technology: • Spring.NET • Managed Extensibility Framework (MEF) • Autofac • Windows Communication Foundation (WCF) • Puzzle.Nfactory • Ninject • PicoContainer.NET • and more
  37. 37. The “Must Read”-Book(s) by Mark SeemannDependencyInjection is a set ofsoftware designprinciples andpatterns thatenable us todevelop looselycoupled code. http://www.manning.com/seemann/
  38. 38. Summary Clean Code - DIMaintainability is achieved through:• Simplification, Specialization Decoupling (KISS, SoC, IoC, DI)• Dependency Injection Constructor Injection as default, Property and Method Injection as needed, Ambient Context for Dependencies with a default, Service Locator never Graphic by Nathan Sawaya courtesy of brickartist.com• Registration Configuration by Convention if possible, exception in Code as needed Configuration by XML for explicit extensibility and post compile setup• Quality through Testability (all of them!)
  39. 39. Q&A Downloads, Feedback & Comments: theo@designitright.net www.designitright.netGraphic by Nathan Sawaya www.speakerrate.com/theojcourtesy of brickartist.com www. slideshare.net/theojungeblut
  40. 40. References…http://www.idesign.net/idesign/DesktopDefault.aspx?tabindex=5&tabid=11http://www.manning.com/seemann/http://en.wikipedia.org/wiki/Keep_it_simple_stupidhttp://picocontainer.org/patterns.htmlhttp://en.wikipedia.org/wiki/Dependency_inversion_principlehttp://en.wikipedia.org/wiki/Dont_repeat_yourselfhttp://en.wikipedia.org/wiki/Component-oriented_programminghttp://en.wikipedia.org/wiki/Service-oriented_architecturehttp://www.martinfowler.com/articles/injection.htmlhttp://www.codeproject.com/KB/aspnet/IOCDI.aspxhttp://msdn.microsoft.com/en-us/magazine/cc163739.aspxhttp://msdn.microsoft.com/en-us/library/ff650320.aspxhttp://msdn.microsoft.com/en-us/library/aa973811.aspxhttp://msdn.microsoft.com/en-us/library/ff647976.aspxhttp://msdn.microsoft.com/en-us/library/cc707845.aspxhttp://msdn.microsoft.com/en-us/library/bb833022.aspxhttp://unity.codeplex.com/ Lego (trademarked in capitals as LEGO)
  41. 41. Please fill out thefeedback, and… www.speakerrate.com/theoj… thanks for you attention!And visit and support the

×