Dependency Injection


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Ultimately, it’s just a fancy name for passing stuff into classes. BUT its ramifications are significant.
  • Dependency Inversion PrincipleHigh-level modules should not depend on low-level modules. Both should depend on abstractionsAbstractions should not depend on details. Details should depend upon abstractions.Your application’s abstractions should be in the BLL, therefore it is wrong for the BLL to depend on the DAL.
  • Encourages SOLID code = plays very nicely with SOLID code. SRP makes composing dependencies easier, amongst other things.
  • DI is a means to achieving loosely-coupled codeThe TV’spower is wired directly into the mains : it’s tightly coupled
  • We can now plug in our laptop insteadUnplugging doesn’t cause either the TV or the wall to explodeWe’ve added an interface!
  • We get new functionalityWe’ve added a Decorator!
  • We can now plug two things into the one socketWe’ve added a Composite!
  • We can now plug in a foreign device, or something small like a camera or phoneWe’ve added an Adapter!
  • Design patterns are building blocks, bricks. How you assemble your bricks mattersAnd this is the great thing about DI: you can add new functionality to new classes (obeying SRP and OCP via decorators), and include it by simply altering the way the application is put together.
  • First one is interesting: EntityBroker is an obvious example, but less obvious examples include the .NET FileSystem classes. Not saying don’t use these, don’t rely on them: DO. Just inject them as dependencies to your class.A Seam is anywhere an interface is used over a concrete the seams of a garment: where an application comes together. E.g., data access layer and business logic layer have a seam.
  • Stable Dependencies: essentially any framework (e.g., ASP.NET MVC, Unit Testing), the BCL, IoC containersSome exceptions to the “Don’t inject the BCL” rule: if a dependency is not easily mockable, such as HttpContext which is a sealed class, wrap it in an interface and Adapter, and inject that.
  • Three dimensions of DI. Object Composition: building a graph of dependenciesLifetime Management: creating new instances of dependencies, scoping dependencies appropriately, correctly disposing of dependencies when they are no longer neededInterception:Application of the Decorator patternAspect-Oriented Programming
  • Single Repsonsibility Principle states that a class should only have one reason to change. If a class is manually managing its dependencies by creating them, that is a reason to change. To adhere to the SRP, the class must surrender control of its dependencies; you regain control of those dependencies through the container.
  • In the previous slide, we removed the ability to create dependencies. As a result, we lose the ability to dispose of them as well, and we must fully delegate management of the object’s lifetime up the stack.Choosing the right one is important for application performance and avoiding resource leaksDo not confuse the Singleton lifetime with the Singleton pattern!
  • Abstractions that are disposable are leaky abstractions: i.e., it betrays detail about the expected implementation behaviour. Even if you have a particular implementation in mind, avoid the urge to mark the interface as IDisposable. It’s like saying your IMainsPlug is an IWatchable: you can watch a PS3, but it’ll be waaay less interesting than watching a TV. .NET Framework guidelines insist that if a class holds an IDisposable member, it should itself implement IDisposable so that it can dispose of the disposable members. If you have a dependency with Singleton scope injected into a class that, and the class follows this recommendation, you will start seeing ObjectDisposedExceptions all over your code.Ephemeral Disposables are common in WCF: channels are created and disposed for each service operation. This is a complicated topic and I can’t do it proper justice here. See Chapter 8 for the full story.
  • Cross-Cutting Concerns are areas of the application that need to be applied to all levels of the application, and that can be considered as common functionality required by many applications. I.e., NOT application-specificNote that they are separate from cross-cutting entities, which should be avoided. Cross-cutting entities are business objects valid in any layer of your application; however, “when entities are allowed to travel between layers, the layers basically collapse. UI concerns and data access concerns will inevitably be mixed up. You may think you have layers, but you don’t.” (, Units
  • Both [PrincipalPermission] and [HandleError] are examples from the .NET framework: the BCL and ASP.NET MVC respectively.
  • Must re-compile code in order to change behaviour based on the attributes defined.Attributes can only be applied in certain places: type definitions, method definitions, etc.Attributes can only have simple constructors because of how they are used. Can’t pass in instance variables, local variables, etc.
  • Decorator isa great pattern for intercepting and modifying behaviour on the fly. However, it results in a lot of repetitive boilerplate code. We can instead take advantage of an IoC container-level feature, where supported, to achieve full dynamic interception.Container dynamically emits new types implementing the required aspect. You must still write the code to implement the aspect, but then you can just tell the container about the aspect and when to apply it. Usually a case of implementing an interface defined by the IoC container for the interceptor. Sometimes you might need to do the same for the interception itself as well. Ninject.Extensions.Interception provides IInterceptor and IInvocation interfaces. IInterceptor defines a single method, Intercept(IInvocation), but it’s recommended to use either ActionInterceptor or SimpleInterceptor if you can.
  • Volatile dependencies = dependencies thatintroduce the need to configure an external environmentare still in developmentaren’t installed on all machines in the development organisationComposition Root is not always the application bootstrapper; in web applications, for example, it might be the beginning of a request. Depends on the framework you’re using (if any).
  • Example: Blog.BusinessLogic.Implementation.PostService
  • .NET Example: System.ComponentModel.IComponent.Site takes an ISite, which is mostly used by Visual Studio to support extra designer functionality.One of many ways of implementing the Open-Closed Principle.Example: Blog.BusinessLogic.Implementation.PostService.TagService (contrived example)
  • No example in my Blog sample, just couldn’t come up with one. Example in the book is one of a currency convertor.NET examples: System.ComponentModel.TypeConverter.ConvertTo() takes an ITypeDescriptorContext; IModelBinder.BindModel() takes a ControllerContext and a ModelBindingContext.Whilst Constructor Injection is useful for applications built on frameworks, Method Injection can be particularly useful for building frameworks themselves. Counter-example: IRatingAlgorithm.CalculateRating: neither the Rating nor the integer “score” parameters are dependencies, so this is not an example of Method Injection.
  • Should only be used in the rarest of cases: please avoid static dependencies, not least because it makes unit testing really hard!Querying the dependency: don’t use for e.g., Logging, where all methods of the dependency return void. This situation is better modelled using Interception.Examples from the BCL: Thread.CurrentPrincipal, Thread.Current[UI]CultureExample: LoggingService
  • No easy sample to show for this one, unfortunately.
  • Ayende talk, November 2010. A question he gets asked a lot is how he manages to do so much stuff. Aim: get to “done” as quickly and easily as possible.Nested Composite Design  • Very modular  • Layered from very low-level to high-level  • Manages complexity very well  • High orthogonality  • Requires some kind of container  • Self-composing  • Loose components  • Lends itself well to extensibilityWhy?  • Attack the problem in small increments  • whole is greater than sum of its parts  • naturally creates isolated pieces of code  • users can touch just one partDependency Injection enables this.
  • IDependencyResolver is intended to be used as a Service Locator (Antipattern!), and is used by ASP.NET MVC as such. It also lacks a Release() method, meaning that objects cannot be cleaned up after use: we’ve lost the ability to manage object lifetime, and so it will cause resource leaks when used in conjunction with some DI containers like Castle Windsor. However, some containers (e.g. Ninject) implement IDependencyResolver to hook the container into MVC. This is ok as the use is tightly restricted and regulated; no dependencies other than the container, which has no lifetime difficulties of its own, are resolved this way.
  • Poor design choice in WPF: DataContext is a property, which implies the dependency is optional. However, the DataContext is not optional when developing in MVVM, the pattern prescribed for WPF development by… Microsoft!
  • Hard work, but not impossible.Because the Page class is now our composition root, its responsibility is to compose the dependencies and we must delegate the actual page logic elsewhere. MVP the key. Keep Presenters in a separate PresentationLogic assembly with no reference to System.Web: that’s the View layer.Alternative is to use a Service Locator, which is a Bad Thing™, particularly here as it clouds the responsibility of the Page class. Unfortunately this is the approach that Viewer currently takes.
  • 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