Dependency Injection with Unity 2.0<br />DmytroMindra<br />RnD Tech Lead<br />Lohika<br />AGILEBASECAMP<br />Lviv, 2011<br />
Goal<br />Get DI understanding<br />
Plan<br />Inversion of Control (IoC)<br />Dependency Injection pattern (DI)<br />Dependency inversion principle<br />Unity...
Problem<br />
Problem<br />We live in an age where writing software to a given set of requirements is no longer enough.<br />We have to ...
Fragile ( errors occur on almost every change)
Immobile (not reusable)</li></li></ul><li>How?<br />Our solutions should be:<br />Modular<br />Testable<br />Adaptive to c...
Terms<br />Service —An object that performs a well-defined function when called upon<br />Client —Any consumer of a servic...
Terms<br />Dependency —A specific service that is required by another object to fulfill its function.<br />Dependent —A cl...
OLD SCHOOL (pre DI STYLE)<br />
Ex1:Composition<br />
Ex1:Composition<br />public class SpellCheckerService{}<br />public class TextEditor<br />    {<br />private SpellCheckerS...
What’s good<br />It’s simple<br />
What’s bad<br />It’s not testable<br />It’s hard to maintain/change<br />
Better approach<br />Dependency Inversion<br />High-level modules should not depend on low-level modules. Both should depe...
Context<br />Context<br />
Ex2:Loose Coupling<br />    public class TextEditor<br />    {<br />private readonlyISpellCheckerService _spellCheckerServ...
Ex2: Unit Testing<br />// Mock <br />ISpellCheckerService mock = new SpellCheckerServiceMock();<br />// Instantiate<br />T...
What changed<br />TextEditor lost its “Sovereignty” and is not able to resolve dependencies by himself.<br />
What’s good<br />Dependencies are obvious.<br />Dependency resolution is not encapsulated.<br />Unit Testing is applicable...
What’s bad<br />We are resolving dependencies manually while creating instances of TextEditor.<br />
Wiring By Hand<br />
Using Factory<br />
Factory<br />
What changed<br />Any required combination of Text Editor and Spell Checking Service is created by object factory.<br />
What’s good<br />It’s testable<br />No manual wiring<br />
What’s bad<br />You have to maintain factory or service locator<br />The more combinations the more methods we have in fac...
Service Locator<br />Unfortunately, being a kind of Factory, Service Locators suffer from the same problems<br />of testab...
What are we looking for?<br />
Inversion of Control<br />Hollywood Principle: <br />Don’t call me, I’ll call you<br />
Inversion of Control<br />IoC –  is a common characteristic of frameworks.<br />According to Martin Fowler the etymology  ...
Dependency Injection<br />DI is a kind of IoC<br />Inversion of Control is too generic a term<br />DI pattern – describes ...
We have alreadyprepared basis.<br />Loosely <br />coupled <br />structure<br />
It’s time to introducenew role<br />Injector <br />(sometimes referred to as a provider or container)<br />
Depedndecy Injection<br />DI in general consists of <br />a dependent consumers<br />their service dependencies<br />and a...
Unity<br />
Ex3: Unity<br />using Microsoft.Practices.Unity;<br />UnityContainer container = new UnityContainer();<br />container.Regi...
What changed<br />Unity container now resolves dependencies<br />
What’s good<br />Automated dependency resolution<br />Business logic and infrastructure are decoupled.<br />
Injection Types<br />Interface injection (by Martin Fowler)<br />Constructor Injection (by Martin Fowler)<br />Setter inje...
Unity methods<br />RegisterType<br />RegisterInstance<br />Resolve<br />BuildUp<br />
Ex4: Unity Configuration<br />	  <configSections>   <section name="unity" type="Microsoft.Practices.Unity.Configuration.Un...
Ex4: Unity Configuration<br />	using Microsoft.Practices.Unity;using Microsoft.Practices.Unity.Configuration;UnityContaine...
Dependency tree<br />
Ex5: Dependency tree<br />public interface IAdditionalDependency{}<br />public class AdditionalDependency : IAdditionalDep...
Ex5: Dependency Tree<br />UnityContainer container = new UnityContainer();container.RegisterType<ISpellCheckerService, 			...
Ex5: Dependency tree<br />
Ex6: Defining Injection Constructor<br />    public class TextEditor    {        private readonly ISpellCheckerService _sp...
Ex7: Property Injection<br />    public class TextEditor    {        public ISpellCheckerService SpellCheckerService {get;...
Ex8: Method call injection<br />    public class TextEditor    {        public ISpellCheckerService SpellcheckerService {g...
Lifetime Managers<br />TransientLifetimeManagerReturns a new instance of the requested type for each call. (default behavi...
Lifetime Managers<br />ExternallyControlledLifetimeManagerImplements a singleton behavior but the container doesn't hold a...
Lifetime Managers<br />PerResolveLifetimeManagerImplements a behavior similar to the transient lifetime manager except tha...
Ex9: Unity Singleton<br />UnityContainer container = new UnityContainer();container.RegisterType<ISpellCheckerService, Spe...
Container Hierarchy<br />
Unity Limitations<br /><ul><li>When your objects and classes have no dependencies on other objects or classes.
When your dependencies are very simple and do not require abstraction. </li></li></ul><li>Performance<br />
Performance<br />
Performance<br />
What DI stands for<br />For<br />Wiring framework components<br />Not for<br />Wiring small parts<br />
Structure MAP<br />
Structure Map Example<br />// Bootstrap<br />Container container =                new Container(x => x.For<ISpellCheckingS...
Compared to Unity <br />// Bootstrap<br />UnityContainer container = new UnityContainer();container.RegisterType<ISpellChe...
Unity vsStructureMap<br />Unity<br />XML Configuration<br />In Code configuration<br />Attributes<br />Benefits<br />Easy ...
.NET DI Frameworks<br />Unity 2.0<br />AutoFac 2.4.3<br />StructureMap 2.6.1<br />Castle Windsor 2.5.3<br />Ninject 2.0<br />
SCOPE, Context, Lifetime<br />
Singleton scope<br />Singleton scoped objects lifetime is bound to injector lifetime.<br />
Difference<br />Singleton scoped object vs. singleton anti pattern<br />
No scope<br />
Connection pool<br />
Web request scope<br />HTTP protocol is stateless and web request scope is quite natural for web applications<br />
Session scope<br />Session is an abstraction that  hides HTTP stateless nature. Such scope should be used carefully.<br />
Circular References<br />
Circular References<br />Objects depend on each other forming cycle in dependency graph.<br />
General case<br />A depends on B<br />B depends on A<br />
Introducing proxy<br />
Diagram<br />Dynamic proxy is constructed<br />
Sequence<br />1. Instantiate Proxy A<br />2. Instantiate B using Proxy A<br />3. Instantiate A using B from step 2<br />4....
Granny and APPLES<br />REINJECTION<br />
G&A Diagram<br />Granny receives concrete apple via injection.<br />Granny eats apple<br />
G&A Sequence<br />Granny needs apples for proper operation<br />New apples should be injected runtime<br />
G&A Solution<br />Instead of single apple we should inject apple “provider”<br />
G&A New Sequence<br />
Drawback<br />If you want produced instances to be configured by general injection rules then your factories will depend o...
GUICE AND Spring<br />
History<br />Spring project brought DI to mainstream.<br />And thank Spring Guice appeared.<br />Guice introduced new feat...
Spring<br />Spring holds a huge DI market share. More than 80%. <br />Proven enterprise solution<br />DI is only a small p...
Guice<br />New kid on the block<br />Introduced new features based on Java 5 support. ( e.g. Provider methods to circumven...
Spring or Guice<br />In DI Spring and Guice are almost equal.<br />Guice provides only DI<br />DI in Spring is only a part...
Where to use Guice<br />If you are sure that you do not need full Spring functionality and your project is not a huge ente...
Patterns<br />Builder<br />Wrapper<br />Adapter<br />Abstract Factory and Factory method<br />
Additional reading<br />
Additional reading<br />
Live Demo<br />
ASP.NET MVC<br />
Questions ?<br />
Thank YOU !<br />
Upcoming SlideShare
Loading in …5
×

Dependency Injection або Don’t call me, I’ll call you

2,834 views

Published on

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

No Downloads
Views
Total views
2,834
On SlideShare
0
From Embeds
0
Number of Embeds
90
Actions
Shares
0
Downloads
81
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Dependency Injection або Don’t call me, I’ll call you

  1. 1. Dependency Injection with Unity 2.0<br />DmytroMindra<br />RnD Tech Lead<br />Lohika<br />AGILEBASECAMP<br />Lviv, 2011<br />
  2. 2. Goal<br />Get DI understanding<br />
  3. 3. Plan<br />Inversion of Control (IoC)<br />Dependency Injection pattern (DI)<br />Dependency inversion principle<br />Unity 2.0, StructureMap<br />Guice, Spring<br />Live ASP.NET MVC Demo<br />
  4. 4. Problem<br />
  5. 5. Problem<br />We live in an age where writing software to a given set of requirements is no longer enough.<br />We have to maintain and change existing code.<br />Code quality ( What’s Bad )R.Martin 1996<br /><ul><li>Rigid (hard to modify)
  6. 6. Fragile ( errors occur on almost every change)
  7. 7. Immobile (not reusable)</li></li></ul><li>How?<br />Our solutions should be:<br />Modular<br />Testable<br />Adaptive to change<br />
  8. 8. Terms<br />Service —An object that performs a well-defined function when called upon<br />Client —Any consumer of a service; an object that calls upon a service to perform a well-understood function<br />
  9. 9. Terms<br />Dependency —A specific service that is required by another object to fulfill its function.<br />Dependent —A client object that needs a dependency (or dependencies) in order to perform its function.<br />
  10. 10. OLD SCHOOL (pre DI STYLE)<br />
  11. 11. Ex1:Composition<br />
  12. 12. Ex1:Composition<br />public class SpellCheckerService{}<br />public class TextEditor<br /> {<br />private SpellCheckerService _spellCheckerService;<br />public TextEditor()<br /> {<br /> _spellCheckerService = new SpellCheckerService(); <br /> }<br /> }<br />class Program<br /> {<br />static void Main(string[] args)<br /> {<br />TextEditor textEditor = new TextEditor();<br /> }<br /> }<br />
  13. 13. What’s good<br />It’s simple<br />
  14. 14. What’s bad<br />It’s not testable<br />It’s hard to maintain/change<br />
  15. 15. Better approach<br />Dependency Inversion<br />High-level modules should not depend on low-level modules. Both should depend on abstractions.<br />Abstractions should not depend upon details. Details should depend upon abstractions.<br /> Robert C. Martin 1996<br />
  16. 16. Context<br />Context<br />
  17. 17. Ex2:Loose Coupling<br /> public class TextEditor<br /> {<br />private readonlyISpellCheckerService _spellCheckerService;<br />public TextEditor(ISpellCheckerServicespellCheckerService)<br /> {<br /> _spellCheckerService = spellCheckerService;<br /> }<br />public string CheckSpelling()<br /> {<br /> return _spellCheckerService.CheckSpelling();<br /> }<br /> }<br />
  18. 18. Ex2: Unit Testing<br />// Mock <br />ISpellCheckerService mock = new SpellCheckerServiceMock();<br />// Instantiate<br />TextEditortextEditor = new TextEditor(mock);<br />// Check<br />Assert.AreEqual(“Mock”, textEditor.CheckSpelling());<br />
  19. 19. What changed<br />TextEditor lost its “Sovereignty” and is not able to resolve dependencies by himself.<br />
  20. 20. What’s good<br />Dependencies are obvious.<br />Dependency resolution is not encapsulated.<br />Unit Testing is applicable<br />Architecture is much better<br />
  21. 21. What’s bad<br />We are resolving dependencies manually while creating instances of TextEditor.<br />
  22. 22. Wiring By Hand<br />
  23. 23.
  24. 24.
  25. 25.
  26. 26.
  27. 27.
  28. 28.
  29. 29. Using Factory<br />
  30. 30. Factory<br />
  31. 31. What changed<br />Any required combination of Text Editor and Spell Checking Service is created by object factory.<br />
  32. 32. What’s good<br />It’s testable<br />No manual wiring<br />
  33. 33. What’s bad<br />You have to maintain factory or service locator<br />The more combinations the more methods we have in factory.<br />Your code knows about the specific factory or factory interface. This means that infrastructure logic is mixed with business logic.<br />Factory may have states.<br />
  34. 34. Service Locator<br />Unfortunately, being a kind of Factory, Service Locators suffer from the same problems<br />of testability and shared state.<br />
  35. 35. What are we looking for?<br />
  36. 36. Inversion of Control<br />Hollywood Principle: <br />Don’t call me, I’ll call you<br />
  37. 37. Inversion of Control<br />IoC –  is a common characteristic of frameworks.<br />According to Martin Fowler the etymology of the phrase dates back to 1988.<br />
  38. 38. Dependency Injection<br />DI is a kind of IoC<br />Inversion of Control is too generic a term<br />DI pattern – describes the approach used to lookup a dependency. <br />Dependency resolution is moved to Framework.<br />
  39. 39. We have alreadyprepared basis.<br />Loosely <br />coupled <br />structure<br />
  40. 40. It’s time to introducenew role<br />Injector <br />(sometimes referred to as a provider or container)<br />
  41. 41. Depedndecy Injection<br />DI in general consists of <br />a dependent consumers<br />their service dependencies<br />and an injector<br />
  42. 42. Unity<br />
  43. 43. Ex3: Unity<br />using Microsoft.Practices.Unity;<br />UnityContainer container = new UnityContainer();<br />container.RegisterType<ISpellCheckerService, SpellCheckingService>();<br />TextEditortextEditor = container.Resolve<TextEditor>();<br />
  44. 44. What changed<br />Unity container now resolves dependencies<br />
  45. 45. What’s good<br />Automated dependency resolution<br />Business logic and infrastructure are decoupled.<br />
  46. 46. Injection Types<br />Interface injection (by Martin Fowler)<br />Constructor Injection (by Martin Fowler)<br />Setter injection (by Martin Fowler)<br />Method call injection (Unity)<br />Method decorator injection (Guice)<br />
  47. 47. Unity methods<br />RegisterType<br />RegisterInstance<br />Resolve<br />BuildUp<br />
  48. 48. Ex4: Unity Configuration<br />   <configSections>   <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>  </configSections>  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">    <alias alias="ISpellCheckerService" type="Unity.Config.ISpellCheckerService, Unity.Config" />    <alias alias="SpellCheckingService" type="Unity.Config.SpellCheckingService, Unity.Config" />    <namespace name="Unity.Config" />    <assembly name="Unity.Config" />    <container>      <register type="ISpellCheckerService" mapTo="SpellCheckingService" />    </container>  </unity><br />
  49. 49. Ex4: Unity Configuration<br /> using Microsoft.Practices.Unity;using Microsoft.Practices.Unity.Configuration;UnityContainer container = new UnityContainer();container.LoadConfiguration();TextEditor textEditor = container.Resolve<TextEditor>();<br />
  50. 50. Dependency tree<br />
  51. 51. Ex5: Dependency tree<br />public interface IAdditionalDependency{}<br />public class AdditionalDependency : IAdditionalDependency{}<br />public class SpellCheckingService: ISpellCheckerService<br /> {        public SpellCheckingService( IAdditionalDependency dependency){}<br />  }<br />
  52. 52. Ex5: Dependency Tree<br />UnityContainer container = new UnityContainer();container.RegisterType<ISpellCheckerService,  SpellCheckingService>();container.RegisterType<IAdditionalDependency, <br />AdditionalDependency>();TextEditor textEditor = container.Resolve<TextEditor>();<br />
  53. 53. Ex5: Dependency tree<br />
  54. 54. Ex6: Defining Injection Constructor<br />    public class TextEditor    {        private readonly ISpellCheckerService _spellCheckerService;        [InjectionConstructor]                public TextEditor(ISpellCheckerService spellCheckerService)        {            _spellCheckerService = spellCheckerService;        }        public TextEditor(ISpellCheckerService spellCheckerService,string name)        {            _spellCheckerService = spellCheckerService;        }    }<br />
  55. 55. Ex7: Property Injection<br />    public class TextEditor    {        public ISpellCheckerService SpellCheckerService {get; set;}        [Dependency]        public ISpellCheckerService YetAnotherSpellcheckerService{get;set;}    }<br />            UnityContainer container = new UnityContainer();            container.RegisterType<TextEditor>(new InjectionProperty("SpellCheckerService"));            container.RegisterType<ISpellCheckerService, SpellCheckingService>();            TextEditor textEditor = container.Resolve<TextEditor>();<br />
  56. 56. Ex8: Method call injection<br />    public class TextEditor    {        public ISpellCheckerService SpellcheckerService {get; set;}<br />        [InjectionMethod]        public void Initialize (ISpellCheckerService spellcheckerService)        {            _spellCheckerService = spellcheckerService;        }    <br />}<br />UnityContainer container = new UnityContainer();//container.RegisterType<TextEditor>(<br /> new InjectionMethod("SpellcheckerService"));container.RegisterType<ISpellCheckerService, SpellCheckingService>();TextEditor textEditor = container.Resolve<TextEditor>();<br />
  57. 57. Lifetime Managers<br />TransientLifetimeManagerReturns a new instance of the requested type for each call. (default behavior)<br />ContainerControlledLifetimeManagerImplements a singleton behavior for objects. The object is disposed of when you dispose of the container. <br />
  58. 58. Lifetime Managers<br />ExternallyControlledLifetimeManagerImplements a singleton behavior but the container doesn't hold a reference to object which will be disposed of when out of scope. <br />HierarchicalifetimeManagerImplements a singleton behavior for objects. However, child containers don't share instances with parents.<br />
  59. 59. Lifetime Managers<br />PerResolveLifetimeManagerImplements a behavior similar to the transient lifetime manager except that instances are reused across build-ups of the object graph. <br />PerThreadLifetimeManagerImplements a singleton behavior for objects but limited to the current thread.<br />
  60. 60. Ex9: Unity Singleton<br />UnityContainer container = new UnityContainer();container.RegisterType<ISpellCheckerService, SpellCheckingService>(new ContainerControlledLifetimeManager());TextEditor textEditor = container.Resolve<TextEditor>();<br />
  61. 61. Container Hierarchy<br />
  62. 62. Unity Limitations<br /><ul><li>When your objects and classes have no dependencies on other objects or classes.
  63. 63. When your dependencies are very simple and do not require abstraction. </li></li></ul><li>Performance<br />
  64. 64. Performance<br />
  65. 65. Performance<br />
  66. 66. What DI stands for<br />For<br />Wiring framework components<br />Not for<br />Wiring small parts<br />
  67. 67. Structure MAP<br />
  68. 68. Structure Map Example<br />// Bootstrap<br />Container container =                new Container(x => x.For<ISpellCheckingService>().                                     Use<FrenchSpellCheckingService>());// Use<br />TextEditor textEditor = container.GetInstance<TextEditor>();<br />
  69. 69. Compared to Unity <br />// Bootstrap<br />UnityContainer container = new UnityContainer();container.RegisterType<ISpellCheckingService, <br />EnglishSpellCheckingService>();// Using containerTextEditor textEditor = container.Resolve<TextEditor>();<br />
  70. 70. Unity vsStructureMap<br />Unity<br />XML Configuration<br />In Code configuration<br />Attributes<br />Benefits<br />Easy code initialization<br />Good documentation<br />StructureMap<br />XML Configuration<br />In Code configuration<br />Attributes<br />Benefits<br />Http & Session lifetime managers out of the box.<br />Convenient XML configuration.<br />
  71. 71. .NET DI Frameworks<br />Unity 2.0<br />AutoFac 2.4.3<br />StructureMap 2.6.1<br />Castle Windsor 2.5.3<br />Ninject 2.0<br />
  72. 72. SCOPE, Context, Lifetime<br />
  73. 73. Singleton scope<br />Singleton scoped objects lifetime is bound to injector lifetime.<br />
  74. 74. Difference<br />Singleton scoped object vs. singleton anti pattern<br />
  75. 75. No scope<br />
  76. 76. Connection pool<br />
  77. 77. Web request scope<br />HTTP protocol is stateless and web request scope is quite natural for web applications<br />
  78. 78. Session scope<br />Session is an abstraction that hides HTTP stateless nature. Such scope should be used carefully.<br />
  79. 79. Circular References<br />
  80. 80. Circular References<br />Objects depend on each other forming cycle in dependency graph.<br />
  81. 81. General case<br />A depends on B<br />B depends on A<br />
  82. 82. Introducing proxy<br />
  83. 83. Diagram<br />Dynamic proxy is constructed<br />
  84. 84. Sequence<br />1. Instantiate Proxy A<br />2. Instantiate B using Proxy A<br />3. Instantiate A using B from step 2<br />4. Initialize Proxy A with A<br />Proxy A passes all requests to concrete A <br />
  85. 85. Granny and APPLES<br />REINJECTION<br />
  86. 86. G&A Diagram<br />Granny receives concrete apple via injection.<br />Granny eats apple<br />
  87. 87. G&A Sequence<br />Granny needs apples for proper operation<br />New apples should be injected runtime<br />
  88. 88. G&A Solution<br />Instead of single apple we should inject apple “provider”<br />
  89. 89. G&A New Sequence<br />
  90. 90. Drawback<br />If you want produced instances to be configured by general injection rules then your factories will depend on concrete injection framework.<br />Google Guice has special interface to support such behavior but you’ll depend on googleGuice. <br />No silver bullet.<br />
  91. 91. GUICE AND Spring<br />
  92. 92. History<br />Spring project brought DI to mainstream.<br />And thank Spring Guice appeared.<br />Guice introduced new features and stimulated further Spring development.<br />Now Guice and Spring are almost equal in DI field and which one to use depends on developer.<br />
  93. 93. Spring<br />Spring holds a huge DI market share. More than 80%. <br />Proven enterprise solution<br />DI is only a small part of its functionality<br />Supports all major injection approaches<br />Current version 3<br />
  94. 94. Guice<br />New kid on the block<br />Introduced new features based on Java 5 support. ( e.g. Provider methods to circumvent type erasure)<br />First-class error messaging.<br />Very fast.<br />Provides only DI<br />Current version 2 ( Version 3 RC )<br />
  95. 95. Spring or Guice<br />In DI Spring and Guice are almost equal.<br />Guice provides only DI<br />DI in Spring is only a part of functionality<br />Google extensively uses Guice<br />Guice is trendy and developers just want to give it a try.<br />So which framework to use heavily depends on project and concrete developer ( team)<br />
  96. 96. Where to use Guice<br />If you are sure that you do not need full Spring functionality and your project is not a huge enterprise level application then you can give it a try.<br />Spring is standard de facto in the industry.<br />
  97. 97. Patterns<br />Builder<br />Wrapper<br />Adapter<br />Abstract Factory and Factory method<br />
  98. 98. Additional reading<br />
  99. 99. Additional reading<br />
  100. 100. Live Demo<br />
  101. 101. ASP.NET MVC<br />
  102. 102. Questions ?<br />
  103. 103. Thank YOU !<br />
  104. 104. References<br />1. Martin Fowler – Dependency Injection<br />http://martinfowler.com/articles/injection.html<br />2. DI Comix<br />http://www.bonkersworld.net/2010/08/11/programmers-only-shaving-who/<br />3. Consultants comix<br />http://stuffthathappens.com/blog/2007/09/26/comic-tribute-to-crazy-bob/<br />4. R. Martin - Dependency Inversion principle<br />http://www.objectmentor.com/resources/articles/dip.pdf<br />

×