Embarrassing coupling problem?        Let’s solve that withDependency Injection           Cory House     @housecor | bitna...
Here’s the plan•   Why•   Composition root•   Injection locations•   Poor man’s DI•   Contrast IoC containers•   Configura...
Tightly coupledLoosely coupled
Inversion of ControlDependency InjectionASP.Net Page Lifecycle
Why DI?Object compositionTestabilityMaintainabilityLifetime ManagementPerformanceLate bindingExtensibilityParallel develop...
SOLID
Code to an abstraction, not an implementation
Interfaces
Tightly coupledLoosely coupled
Collaborating classes shouldrely on infrastructure toprovide services.
Demo: Poor man’s DI
Is new evil?var user = new User()
Watch for Volatilitynew StringBuilder()     App specificnew List<T>()              new User, Product, OrderSystem.Xml     ...
Composition Root•   Where the app “starts”•   Classes are composed here•   Keeps app unaware of the IoC container•   Uniqu...
Composition RootTechnology          Composition RootConsole App         Main methodASP.NET MVC         Call custom IContro...
Register, Resolve, Release
Injection Location1. Constructor2. Property3. MethodLocation    Usage              Benefits             DrawbacksConstruct...
Config Styles1.XML2.Code (aka fluent)3.Auto-registration
Demo: Config Styles
Config Styles                    Mapping    Advantages              Disadvantages           XML      Config     Late bindi...
Config Style SupportStyle               Castle Windsor   StructureMap Spring.Net Autofac   UnityXML                       ...
ExplicitXML                                   Code as                                      Configuration  Late Binding    ...
LifestylesLifestyle         Description                     UsageSingleton         Once on App startup. Most       Thread ...
Lifestyle SupportLifestyle   Castle     StructureMap   Spring.Net   Autofac   Unity            WindsorSingleton      X    ...
WarningWindsor: SingletonStructureMap: TransientRelease transients or burn all RAM
Demo: Coupling
Control Freak
Control Freak: Solutions• Factory – moves             • Constructor or property  problem to another            injection  ...
Service Locator: Anti-pattern? Service Locator:     Ask for        DI: Consumer   dependency          supplies            ...
Demo: Service Locator
Problems with Service Locator• Hides dependencies• IoC container tightly coupled• Drags in other modules if IoC container ...
Anti-Patterns: Bastard Injection                            Foreign                            Default
Bastard Injection1. Overloaded constructor = ambiguity2. Often introduces foreign dependency3. Hinders parallel developmen...
Other Anti-Patterns•   Factory that references config•   Constructor over injection•   MVC’s Idependency Resolver•   Abstr...
Cross-Cutting Concerns   Presentation                  Auditing,                  Logging,     Domain       Security,     ...
Cross-cutting concernsProblems:           Solution: Dynamic ProxiesAuditing            Decorator PatternLogging           ...
Cross-cutting concernsTwo approaches:1. Dynamic Proxies2. IL Weaving
PostSharp               Normal       PostSharp      .NetAttributes             Compilation   Compilation   Assembly
AOP via attributes1. Modify compilation  •   PostSharp2. Custom runtime host  •   WCF  •   ASP.Net MVC  •   Unit testing f...
AOP via attributes• No special design effort    • Code runs different from• Easy to spot since inline     the code you wro...
How do I choose a container?PerformanceLifetimesDocumentationAPISupportDynamic proxies
Summary1. Compose at composition root2. Prefer constructor injection, auto-registration3. Volatility? Think smoke detector...
Next Steps
Thanks for listening!@housecor | bitnative.com
Example project on GitPerformance Benchmarks
To Do• Remove references to data layer(s) in MVC  project. Surprising that ploeh did it in his, but  clearly a risky issue...
Dependency injection
Upcoming SlideShare
Loading in …5
×

Dependency injection

7,291 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
7,291
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
35
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Ioc: Broad term. Prog style where framework or runtime control the program flow. For example, ASP.Net lifecycleDI – coined by Martin Folweris a set of software design principles and patterns that enable us to develop loosely coupled code. See pg. 42NOTE: Ioc nicely describes exactly what we’re trying to do.
  • See table page 16Late binding – replace services without recompile
  • SRP - an object should have only a single responsibilityOpen/Closed - open for extension, but closed for modificationLiskovSubstution Principle - objects in a program should be replaceable with instances of their subtypesInterface segregation principle - many client-specific interfaces are better than one general-purpose interface.Dependency Inversion principle -  Depend upon Abstractions. Do not depend upon concretions.
  • Abstract class or interface. I’ll use the word interface for simplicity, but either will do.
  • Note, only the enemy when a volatile dependency. .Net BCL dependencies aren’t. new StringBuilder() is fine, unless for some reason it’s not. The amount of coupling in an application is loosely correlated to the number of times you see the new keyword in the codebase.
  • Pg 82 Each app should only have a single reference to each of the above methods. Why, config should be considered a single atomic action. Once resolved, consider the container read only. Be sure to release what you resolve. Naming convention from Castle Windsor.
  • Property: (aka setter – use when a good local default, but want to allow callers to provide alternative assemblies)
  • benefits on pg 68
  • TightlyCoupled project – HomeController.cs
  • HomeController alternative Index method
  • Common when attempting to make class testable without understanding DIBastard Injection 146
  • T
  • Dependency injection

    1. 1. Embarrassing coupling problem? Let’s solve that withDependency Injection Cory House @housecor | bitnative.com
    2. 2. Here’s the plan• Why• Composition root• Injection locations• Poor man’s DI• Contrast IoC containers• Configuration styles• Lifestyles• Anti-patterns• Cross-cutting concerns
    3. 3. Tightly coupledLoosely coupled
    4. 4. Inversion of ControlDependency InjectionASP.Net Page Lifecycle
    5. 5. Why DI?Object compositionTestabilityMaintainabilityLifetime ManagementPerformanceLate bindingExtensibilityParallel developmentCross-cutting concerns (AOP)
    6. 6. SOLID
    7. 7. Code to an abstraction, not an implementation
    8. 8. Interfaces
    9. 9. Tightly coupledLoosely coupled
    10. 10. Collaborating classes shouldrely on infrastructure toprovide services.
    11. 11. Demo: Poor man’s DI
    12. 12. Is new evil?var user = new User()
    13. 13. Watch for Volatilitynew StringBuilder() App specificnew List<T>() new User, Product, OrderSystem.Xml Non-deterministic DateTime.Now, File, Data Slow Remote service
    14. 14. Composition Root• Where the app “starts”• Classes are composed here• Keeps app unaware of the IoC container• Unique techniques for different techs
    15. 15. Composition RootTechnology Composition RootConsole App Main methodASP.NET MVC Call custom IControllerFactory in Global.asaxWCF ServiceHostFactory and a few other tricksASP.NET Web Forms Humble object or Service Locator in each aspx.cs
    16. 16. Register, Resolve, Release
    17. 17. Injection Location1. Constructor2. Property3. MethodLocation Usage Benefits DrawbacksConstructor When possible Simple Tricky (some frameworks) Guarantees injection Object graph on startup ExplicitProperty Good local default Easy to understand Not simple to implementMethod Dependency Caller provides Limited applicability varies by method operation specific call context
    18. 18. Config Styles1.XML2.Code (aka fluent)3.Auto-registration
    19. 19. Demo: Config Styles
    20. 20. Config Styles Mapping Advantages Disadvantages XML Config Late binding No compile-time checks Control Verbose Code Code Compile-time checks Must recompile Control IntellisenseAuto-Registration Rules Late binding Partial compile-time checks Automatic = Less work Less control Reinforces conventions Magic
    21. 21. Config Style SupportStyle Castle Windsor StructureMap Spring.Net Autofac UnityXML X X X X XCode X X X XAuto-registration X X X
    22. 22. ExplicitXML Code as Configuration Late Binding Early Binding Auto Registration Implicit
    23. 23. LifestylesLifestyle Description UsageSingleton Once on App startup. Most Thread safe, stateless, efficient. immutable, circuit breaker, in- memory cacheTransient Per Request. Least efficient. Default (most)Per Graph One instance of each Anywhere thread that resolves is dependency per thread the only consumer of the graph. Efficient alt to transient.Web Request One instance per web request Web app requests whenContext singleton won’t workThread Context Per threadSession Context Per sessionPooled Pool of ready objects Expensive to createScopedCustom
    24. 24. Lifestyle SupportLifestyle Castle StructureMap Spring.Net Autofac Unity WindsorSingleton X X X X XTransient X X X X XPer Graph X XWeb X X (X) XRequestContextThread X X XContextSession X (X)ContextPooled XScoped X XCustom X X X
    25. 25. WarningWindsor: SingletonStructureMap: TransientRelease transients or burn all RAM
    26. 26. Demo: Coupling
    27. 27. Control Freak
    28. 28. Control Freak: Solutions• Factory – moves • Constructor or property problem to another injection class• Static factory that calls config – No easy way to inject mock for unit testing.
    29. 29. Service Locator: Anti-pattern? Service Locator: Ask for DI: Consumer dependency supplies dependency
    30. 30. Demo: Service Locator
    31. 31. Problems with Service Locator• Hides dependencies• IoC container tightly coupled• Drags in other modules if IoC container is in separate module
    32. 32. Anti-Patterns: Bastard Injection Foreign Default
    33. 33. Bastard Injection1. Overloaded constructor = ambiguity2. Often introduces foreign dependency3. Hinders parallel development• Fix – Foreign default: Constructor injection – Local default: Property injection
    34. 34. Other Anti-Patterns• Factory that references config• Constructor over injection• MVC’s Idependency Resolver• Abstracting away your container• Web Forms
    35. 35. Cross-Cutting Concerns Presentation Auditing, Logging, Domain Security, Etc. Data
    36. 36. Cross-cutting concernsProblems: Solution: Dynamic ProxiesAuditing Decorator PatternLogging Honor SRPSecurity Honor Open/ClosedError handlingPerf MonitoringCachingFault tolerance
    37. 37. Cross-cutting concernsTwo approaches:1. Dynamic Proxies2. IL Weaving
    38. 38. PostSharp Normal PostSharp .NetAttributes Compilation Compilation Assembly
    39. 39. AOP via attributes1. Modify compilation • PostSharp2. Custom runtime host • WCF • ASP.Net MVC • Unit testing frameworks
    40. 40. AOP via attributes• No special design effort • Code runs different from• Easy to spot since inline the code you wrote• Explicit since in context • Vendor lock-in • Attributes compiled with code = Tightly coupled. • Can’t vary the aspect independently of the implementation • Can’t use conventions
    41. 41. How do I choose a container?PerformanceLifetimesDocumentationAPISupportDynamic proxies
    42. 42. Summary1. Compose at composition root2. Prefer constructor injection, auto-registration3. Volatility? Think smoke detectors vs sockets
    43. 43. Next Steps
    44. 44. Thanks for listening!@housecor | bitnative.com
    45. 45. Example project on GitPerformance Benchmarks
    46. 46. To Do• Remove references to data layer(s) in MVC project. Surprising that ploeh did it in his, but clearly a risky issue since it means others might tightly couple• Add checks in project to protect from bad refs.

    ×