Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
DEPENDENCY INJECTION
PART 1
Alastair Smith (after Mark Seemann)
Agenda
 Overview
 Concepts
 The Scope of Dependency Injection
 Patterns and Anti-Patterns
What is Dependency Injection?
What is Dependency Injection Not?
What Does Dependency Injection BuyYou?
Overview
What is Dependency
Injection?
 A technique
 A collection of patterns for loosely-coupled
code
 Favour composition over ...
What is Dependency Injection
Not?
 Dependency Inversion (the D in SOLID)
 You must first invert your dependencies to
pro...
What Does DI Buy You?
 Testable and maintainable code
 Encourages SOLID code
 Late binding
 Swapping services out for ...
The Purpose of DI
What to Inject (andWhat Not to Inject)
Concepts
Tight Coupling
Wall
How do we decouple?
Wall
How do we get new
functionality?
Wall
UPS
How do we do multiple
things?
Wall
UPS
How do we use an
incompatible device?
Wall
UPS
Design Patterns will only
get you so far
 How you assemble your bricks matters
What to Inject
 VOLATILE DEPENDENCIES
libraries that:
 introduce the need to configure an external
environment
 are sti...
What Not to Inject
 STABLE DEPENDENCIES
libraries or frameworks that:
 won’t introduce breaking changes with new
version...
Object Composition
Lifetime Management
Interception
The Scope of Dependency Injection
Object Composition
 Building object graphs into functional units
 Creating objects
 Creating relationships between obje...
Lifetime Management
 Must invert control of an object’s lifetime
management as well as the dependency itself
 Different ...
A Word on IDisposable
 Complicated by use of Dependency Injection
 Do not mark your abstractions as
IDisposable
 Let th...
Interception
 Applying functionality on the fly
 Used to add Cross-Cutting Concerns:
 Logging
 Auditing
 Performance
...
Aspect-Oriented Programming
 Cross-Cutting Concerns applied via attributes
decorating a method
 [PrincipalPermission]
 ...
AOP Disadvantages
 Attributes are compiled with the code they
adorn
 Can’t easily change behaviour
 Limited options for...
Dynamic Interception
 Can be achieved with liberal use of
Decorators
 Violates DRY
 Lots of boilerplate code
 Containe...
Constructor Injection
Property Injection
Method Injection
Ambient Context
Patterns
Terminology
 COMPOSITION ROOT
 Where the application is assembled
 DEPENDENCY
 AVolatile Dependency from Part 1
 DEFA...
Constructor Injection
 This should be your default choice for DI
 Guarantees that a necessary DEPENDENCY is
always avail...
Property Injection
 Use when a DEPENDENCY is optional
 There should be a good LOCAL DEFAULT
Advantages Disadvantages
Eas...
Method Injection
 Use when a DEPENDENCY varies per call of a
method
 Usually the DEPENDENCY represents some
context for ...
Ambient Context
 Use to inject static DEPENDENCIES
 Only use when querying the dependency
 A proper LOCAL DEFAULT exist...
Control Freak
Bastard Injection
Service Locator
ConstrainedConstruction
Anti-Patterns
Control Freak
 DEPENDENCIES are controlled directly
 E.g., creating an instance of Foo for a field of type
IFoo.
 Usual...
Bastard Injection
 Foreign DEFAULTS are used as default values
for DEPENDENCIES
 E.g., AccountController in ASP.NET MVC
...
Service Locator
 Calling into your IoC container outside of the
COMPOSITION ROOT
 Can tightly-couple your application to...
Constrained Construction
 Constructors are assumed to have a particular
signature
 E.g.,WebForms requires Pages to have ...
Any questions?
End of Part One
DEPENDENCY INJECTION
PART 2
Alastair Smith (after Mark Seemann)
ASP.NET MVC
WPF
WCF
ASP.NET
Manually Composing Applications
ASP.NET MVC
 COMPOSITION ROOT: global.asax +
IControllerFactory
 Can also useWebActivator package from NuGet
 Ignore ID...
WPF with MVVM
 COMPOSITION ROOT:
Application.OnStartup()
 Use Constructor Injection on your
MainWindowViewModel
 Create...
WCF
 COMPOSITION ROOT: triplet of
 ServiceHostFactory
 ServiceHost
 IInstanceProvider
ASP.NET
 Suffers from Constrained Construction
 COMPOSITION ROOT: each Page class
 Single Responsibility Principle
 Mo...
Any questions?
End of Part Two
Upcoming SlideShare
Loading in …5
×

Dependency Injection

1,391 views

Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Dependency Injection

  1. 1. DEPENDENCY INJECTION PART 1 Alastair Smith (after Mark Seemann)
  2. 2. Agenda  Overview  Concepts  The Scope of Dependency Injection  Patterns and Anti-Patterns
  3. 3. What is Dependency Injection? What is Dependency Injection Not? What Does Dependency Injection BuyYou? Overview
  4. 4. What is Dependency Injection?  A technique  A collection of patterns for loosely-coupled code  Favour composition over inheritance  Program to the interface not the implementation  A form of Inversion of Control
  5. 5. What is Dependency Injection Not?  Dependency Inversion (the D in SOLID)  You must first invert your dependencies to properly apply dependency injection Data Access Layer Business Logic Layer Presentation Layer
  6. 6. What Does DI Buy You?  Testable and maintainable code  Encourages SOLID code  Late binding  Swapping services out for other implementations  Easy extensibility  Code can be extended in ways not originally envisaged
  7. 7. The Purpose of DI What to Inject (andWhat Not to Inject) Concepts
  8. 8. Tight Coupling Wall
  9. 9. How do we decouple? Wall
  10. 10. How do we get new functionality? Wall UPS
  11. 11. How do we do multiple things? Wall UPS
  12. 12. How do we use an incompatible device? Wall UPS
  13. 13. Design Patterns will only get you so far  How you assemble your bricks matters
  14. 14. What to Inject  VOLATILE DEPENDENCIES libraries that:  introduce the need to configure an external environment  are still in development  aren’t installed on all machines in the development organisation  E.g.: EntityBroker, Phoenix, SpreadsheetGear  Inject across SEAMS
  15. 15. What Not to Inject  STABLE DEPENDENCIES libraries or frameworks that:  won’t introduce breaking changes with new versions  you never expect to have to replace  E.g.: the BCL
  16. 16. Object Composition Lifetime Management Interception The Scope of Dependency Injection
  17. 17. Object Composition  Building object graphs into functional units  Creating objects  Creating relationships between objects  No more new Foo()  Single Responsibility Principle  Regain control through a DI container  Provides late-binding, extensibility and parallel development benefits
  18. 18. Lifetime Management  Must invert control of an object’s lifetime management as well as the dependency itself  Different lifetime options  Singleton  Per-request  Per-thread  (and others)
  19. 19. A Word on IDisposable  Complicated by use of Dependency Injection  Do not mark your abstractions as IDisposable  Let the DI Container handle disposable implementations  Hide Ephemeral Disposables behind a SEAM  Use an injectedAbstract Factory to create them  Keep their using blocks short
  20. 20. Interception  Applying functionality on the fly  Used to add Cross-Cutting Concerns:  Logging  Auditing  Performance  Access control  Security  ...
  21. 21. Aspect-Oriented Programming  Cross-Cutting Concerns applied via attributes decorating a method  [PrincipalPermission]  [HandleError]  Requires either:  Post-compilation step (e.g., PostSharp), or  A custom host (e.g.,WCF, ASP.NET MVC, NUnit)
  22. 22. AOP Disadvantages  Attributes are compiled with the code they adorn  Can’t easily change behaviour  Limited options for applying attributes  Attributes must have a simple constructor  Makes lifetime management trickier
  23. 23. Dynamic Interception  Can be achieved with liberal use of Decorators  Violates DRY  Lots of boilerplate code  Container-level feature  CastleWindsor, Spring.NET, Unity and Ninject all support it  Neat way to achieve DRY and SOLID code
  24. 24. Constructor Injection Property Injection Method Injection Ambient Context Patterns
  25. 25. Terminology  COMPOSITION ROOT  Where the application is assembled  DEPENDENCY  AVolatile Dependency from Part 1  DEFAULT value  E.g. a no-op, such as a Null Object  Not your default implementation!
  26. 26. Constructor Injection  This should be your default choice for DI  Guarantees that a necessary DEPENDENCY is always available to the class Advantages Disadvantages Injection guaranteed Some frameworks make it difficult Easy to implement
  27. 27. Property Injection  Use when a DEPENDENCY is optional  There should be a good LOCAL DEFAULT Advantages Disadvantages Easy to understand Limited applicability Not entirely simple to implement robustly
  28. 28. Method Injection  Use when a DEPENDENCY varies per call of a method  Usually the DEPENDENCY represents some context for the method call  Limited applicability Advantages Disadvantages Allows the caller to provide operation-specific context Limited applicability
  29. 29. Ambient Context  Use to inject static DEPENDENCIES  Only use when querying the dependency  A proper LOCAL DEFAULT exists  It must be guaranteed available Advantages Disadvantages Doesn’t polluteAPIs Implicit Is always available Hard to implement correctly May not work well in some runtimes
  30. 30. Control Freak Bastard Injection Service Locator ConstrainedConstruction Anti-Patterns
  31. 31. Control Freak  DEPENDENCIES are controlled directly  E.g., creating an instance of Foo for a field of type IFoo.  Usually occurs within a Factory  Root these out of your codebase!  Refactor to Constructor Injection
  32. 32. Bastard Injection  Foreign DEFAULTS are used as default values for DEPENDENCIES  E.g., AccountController in ASP.NET MVC  Refactor towards Constructor Injection  Refactor towards Property Injection  But only if there’s a LOCAL DEFAULT
  33. 33. Service Locator  Calling into your IoC container outside of the COMPOSITION ROOT  Can tightly-couple your application to your IoC container!  Acts as a replacement for new Foo()  Refactor towards Constructor Injection
  34. 34. Constrained Construction  Constructors are assumed to have a particular signature  E.g.,WebForms requires Pages to have a default constructor  No easy refactoring to DI  Some possibilities via Abstract Factory
  35. 35. Any questions? End of Part One
  36. 36. DEPENDENCY INJECTION PART 2 Alastair Smith (after Mark Seemann)
  37. 37. ASP.NET MVC WPF WCF ASP.NET Manually Composing Applications
  38. 38. ASP.NET MVC  COMPOSITION ROOT: global.asax + IControllerFactory  Can also useWebActivator package from NuGet  Ignore IDependencyResolver!  Intended to be a Service Locator  Removes ability to manage object lifetime  IControllerFactory is the appropriate extensibility point  Use Constructor Injection on your Controllers
  39. 39. WPF with MVVM  COMPOSITION ROOT: Application.OnStartup()  Use Constructor Injection on your MainWindowViewModel  Create an IWindow interface and inject this  Implemented by a MainWindowAdapter for each Window  Create a MainWindowViewModelFactory  Needed because there is a circular dependency between theView and theViewModel
  40. 40. WCF  COMPOSITION ROOT: triplet of  ServiceHostFactory  ServiceHost  IInstanceProvider
  41. 41. ASP.NET  Suffers from Constrained Construction  COMPOSITION ROOT: each Page class  Single Responsibility Principle  Model-View-Presenter (MVP)  Keep Presenters fully independent of System.Web
  42. 42. Any questions? End of Part Two

×