SlideShare une entreprise Scribd logo
1  sur  103
Dependency Injection with Unity 2.0 DmytroMindra RnD Tech Lead Lohika AGILEBASECAMP Lviv, 2011
Goal Get DI understanding
Plan Inversion of Control (IoC) Dependency Injection pattern (DI) Dependency inversion principle Unity 2.0, StructureMap Guice, Spring Live ASP.NET MVC Demo
Problem
Problem We live in an age where writing software to a given set of requirements is no longer enough. We have to maintain and change existing code. Code quality ( What’s Bad )R.Martin 1996 ,[object Object]
Fragile ( errors occur on almost every change)
Immobile (not reusable),[object Object]
Terms Service —An object that performs a well-defined function when called upon Client —Any consumer of a service; an object that calls upon a service to perform a well-understood function
Terms Dependency —A specific service that is required by another object to fulfill its function. Dependent —A client object that needs a dependency (or dependencies) in order to perform its function.
OLD SCHOOL (pre DI STYLE)
Ex1:Composition
Ex1:Composition public class SpellCheckerService{} public class TextEditor     { private SpellCheckerService _spellCheckerService; public TextEditor()         {             _spellCheckerService = new SpellCheckerService();            }     } class Program     { static void Main(string[] args)         { TextEditor textEditor = new TextEditor();         }     }
What’s good It’s simple
What’s bad It’s not testable It’s hard to maintain/change
Better approach Dependency Inversion High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend upon details. Details should depend upon abstractions.  Robert C. Martin	1996
Context Context
Ex2:Loose Coupling     public class TextEditor     { private readonlyISpellCheckerService _spellCheckerService; public TextEditor(ISpellCheckerServicespellCheckerService)         {             _spellCheckerService = spellCheckerService;         } public string CheckSpelling()         {             return _spellCheckerService.CheckSpelling();         }     }
Ex2: Unit Testing // Mock  ISpellCheckerService mock = new SpellCheckerServiceMock(); // Instantiate TextEditortextEditor = new TextEditor(mock); // Check Assert.AreEqual(“Mock”, textEditor.CheckSpelling());
What changed TextEditor lost its “Sovereignty” and is not able to resolve dependencies by himself.
What’s good Dependencies are obvious. Dependency resolution is not encapsulated. Unit Testing is applicable Architecture is much better
What’s bad We are resolving dependencies manually while creating instances of TextEditor.
Wiring By Hand
Using Factory
Factory
What changed Any required combination of Text Editor and Spell Checking Service is created by object factory.
What’s good It’s testable No manual wiring
What’s bad You have to maintain factory or service locator The more combinations the more methods we have in factory. Your code knows about the specific factory or factory interface. This means that infrastructure logic is mixed with business logic. Factory may have states.
Service Locator Unfortunately, being a kind of Factory, Service Locators suffer from the same problems of testability and shared state.
What are we looking for?
Inversion of Control Hollywood Principle:  Don’t call me, I’ll call you
Inversion of Control IoC –  is a common characteristic of frameworks. According to Martin Fowler the etymology  of the phrase dates back to 1988.
Dependency Injection DI is a kind of IoC Inversion of Control is too generic a term DI pattern – describes the approach used to lookup a dependency.  Dependency resolution is moved to Framework.
We have alreadyprepared basis. Loosely  coupled  structure
It’s time to introducenew role Injector  (sometimes referred to as a provider or container)
Depedndecy Injection DI in general consists of  a dependent consumers their service dependencies and an injector
Unity
Ex3: Unity using Microsoft.Practices.Unity; UnityContainer container = new UnityContainer(); container.RegisterType<ISpellCheckerService, SpellCheckingService>(); TextEditortextEditor = container.Resolve<TextEditor>();
What changed Unity container now resolves dependencies
What’s good Automated dependency resolution Business logic and infrastructure are decoupled.
Injection Types Interface injection (by Martin Fowler) Constructor Injection (by Martin Fowler) Setter injection (by Martin Fowler) Method call injection (Unity) Method decorator injection (Guice)
Unity methods RegisterType RegisterInstance Resolve BuildUp
Ex4: Unity Configuration 	  <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>
Ex4: Unity Configuration 	using Microsoft.Practices.Unity;using Microsoft.Practices.Unity.Configuration;UnityContainer container = new UnityContainer();container.LoadConfiguration();TextEditor textEditor = container.Resolve<TextEditor>();
Dependency tree
Ex5: Dependency tree public interface IAdditionalDependency{} public class AdditionalDependency : IAdditionalDependency{} public class SpellCheckingService: ISpellCheckerService  {        public SpellCheckingService( IAdditionalDependency dependency){}   }
Ex5: Dependency Tree UnityContainer container = new UnityContainer();container.RegisterType<ISpellCheckerService, 							SpellCheckingService>();container.RegisterType<IAdditionalDependency,  AdditionalDependency>();TextEditor textEditor = container.Resolve<TextEditor>();
Ex5: Dependency tree
Ex6: Defining Injection Constructor     public class TextEditor    {        private readonly ISpellCheckerService _spellCheckerService;        [InjectionConstructor]                public TextEditor(ISpellCheckerService spellCheckerService)        {            _spellCheckerService = spellCheckerService;        }        public TextEditor(ISpellCheckerService spellCheckerService,string name)        {            _spellCheckerService = spellCheckerService;        }    }
Ex7: Property Injection     public class TextEditor    {        public ISpellCheckerService SpellCheckerService {get; set;}        [Dependency]        public ISpellCheckerService YetAnotherSpellcheckerService{get;set;}    }             UnityContainer container = new UnityContainer();            container.RegisterType<TextEditor>(new InjectionProperty("SpellCheckerService"));            container.RegisterType<ISpellCheckerService, SpellCheckingService>();            TextEditor textEditor = container.Resolve<TextEditor>();
Ex8: Method call injection     public class TextEditor    {        public ISpellCheckerService SpellcheckerService {get; set;}         [InjectionMethod]        public void Initialize (ISpellCheckerService spellcheckerService)        {            _spellCheckerService = spellcheckerService;        }     } UnityContainer container = new UnityContainer();//container.RegisterType<TextEditor>( 			new InjectionMethod("SpellcheckerService"));container.RegisterType<ISpellCheckerService, SpellCheckingService>();TextEditor textEditor = container.Resolve<TextEditor>();
Lifetime Managers TransientLifetimeManagerReturns a new instance of the requested type for each call. (default behavior) ContainerControlledLifetimeManagerImplements a singleton behavior for objects. The object is disposed of when you dispose of the container.
Lifetime Managers ExternallyControlledLifetimeManagerImplements a singleton behavior but the container doesn't hold a reference to object which will be disposed of when out of scope.  HierarchicalifetimeManagerImplements a singleton behavior for objects. However, child containers don't share instances with parents.
Lifetime Managers PerResolveLifetimeManagerImplements a behavior similar to the transient lifetime manager except that instances are reused across build-ups of the object graph.  PerThreadLifetimeManagerImplements a singleton behavior for objects but limited to the current thread.
Ex9: Unity Singleton UnityContainer container = new UnityContainer();container.RegisterType<ISpellCheckerService, SpellCheckingService>(new ContainerControlledLifetimeManager());TextEditor textEditor = container.Resolve<TextEditor>();
Container Hierarchy
Unity Limitations ,[object Object]
When your dependencies are very simple and do not require abstraction. ,[object Object]
Performance
Performance
What DI stands for For Wiring framework components Not for Wiring small parts
Structure MAP
Structure Map Example // Bootstrap Container container =                new Container(x => x.For<ISpellCheckingService>().                                     Use<FrenchSpellCheckingService>());// Use TextEditor textEditor = container.GetInstance<TextEditor>();
Compared to Unity  // Bootstrap UnityContainer container = new UnityContainer();container.RegisterType<ISpellCheckingService,  EnglishSpellCheckingService>();// Using containerTextEditor textEditor = container.Resolve<TextEditor>();
Unity vsStructureMap Unity XML Configuration In Code configuration Attributes Benefits Easy code initialization Good documentation StructureMap XML Configuration In Code configuration Attributes Benefits Http & Session lifetime managers out of the box. Convenient XML configuration.
.NET DI Frameworks Unity 2.0 AutoFac 2.4.3 StructureMap 2.6.1 Castle Windsor 2.5.3 Ninject 2.0
SCOPE, Context, Lifetime
Singleton scope Singleton scoped objects lifetime is bound to injector lifetime.
Difference Singleton scoped object vs. singleton anti pattern
No scope
Connection pool
Web request scope HTTP protocol is stateless and web request scope is quite natural for web applications
Session scope Session is an abstraction that  hides HTTP stateless nature. Such scope should be used carefully.
Circular References
Circular References Objects depend on each other forming cycle in dependency graph.
General case A depends on B B depends on A
Introducing proxy
Diagram Dynamic proxy is constructed
Sequence 1. Instantiate Proxy A 2. Instantiate B using Proxy A 3. Instantiate A using B from step 2 4. Initialize Proxy A with A Proxy A passes all requests to concrete A
Granny and APPLES REINJECTION
G&A Diagram Granny receives concrete apple via injection. Granny eats apple
G&A Sequence Granny needs apples for proper operation New apples should be injected runtime
G&A Solution Instead of single apple we should inject apple “provider”
G&A New Sequence
Drawback If you want produced instances to be configured by general injection rules then your factories will depend on concrete injection framework. Google Guice has special interface to support such behavior but you’ll depend on googleGuice.  No silver bullet.
GUICE AND Spring
History Spring project brought DI to mainstream. And thank Spring Guice appeared. Guice introduced new features and stimulated further Spring development. Now Guice and Spring are almost equal in DI field and which one to use depends on developer.
Spring Spring holds a huge DI market share. More than 80%.  Proven enterprise solution DI is only a small part of its functionality Supports all major injection approaches Current version 3
Guice New kid on the block Introduced new features based on Java 5 support. ( e.g. Provider methods to circumvent type erasure) First-class error messaging. Very fast. Provides only DI Current version 2 ( Version 3 RC )
Spring or Guice In DI Spring and Guice are almost equal. Guice provides only DI DI in Spring is only a part of functionality Google extensively uses Guice Guice is trendy and developers just want to give it a try. So which framework to use heavily depends on project and concrete developer ( team)
Where to use Guice 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. Spring is standard de facto in the industry.
Patterns Builder Wrapper Adapter Abstract Factory and Factory method
Additional reading
Additional reading
Live Demo
ASP.NET MVC
Questions ?
Thank YOU !

Contenu connexe

Tendances

Angular Interview Questions & Answers
Angular Interview Questions & AnswersAngular Interview Questions & Answers
Angular Interview Questions & AnswersRatnala Charan kumar
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetdevlabsalliance
 
jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture Jiby John
 
Android Dagger 2
Android  Dagger 2Android  Dagger 2
Android Dagger 2Sanket Shah
 
Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Sunil kumar Mohanty
 
Html5 Interview Questions & Answers
Html5 Interview Questions & AnswersHtml5 Interview Questions & Answers
Html5 Interview Questions & AnswersRatnala Charan kumar
 
Functional programming in C#
Functional programming in C#Functional programming in C#
Functional programming in C#Thomas Jaskula
 
Analyzing source code of WPF examples by the Infragistics Company
Analyzing source code of WPF examples by the Infragistics CompanyAnalyzing source code of WPF examples by the Infragistics Company
Analyzing source code of WPF examples by the Infragistics CompanyPVS-Studio
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit TestingJames Phillips
 
Entity Manager
Entity ManagerEntity Manager
Entity Managerpatinijava
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2Javad Hashemi
 

Tendances (20)

Angular Interview Questions & Answers
Angular Interview Questions & AnswersAngular Interview Questions & Answers
Angular Interview Questions & Answers
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdet
 
jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture
 
Android Dagger 2
Android  Dagger 2Android  Dagger 2
Android Dagger 2
 
Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample
 
Html5 Interview Questions & Answers
Html5 Interview Questions & AnswersHtml5 Interview Questions & Answers
Html5 Interview Questions & Answers
 
Android Dagger2
Android Dagger2Android Dagger2
Android Dagger2
 
Deployment
DeploymentDeployment
Deployment
 
Functional programming in C#
Functional programming in C#Functional programming in C#
Functional programming in C#
 
Analyzing source code of WPF examples by the Infragistics Company
Analyzing source code of WPF examples by the Infragistics CompanyAnalyzing source code of WPF examples by the Infragistics Company
Analyzing source code of WPF examples by the Infragistics Company
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
 
Android services internals
Android services internalsAndroid services internals
Android services internals
 
Ejb6
Ejb6Ejb6
Ejb6
 
Entity Manager
Entity ManagerEntity Manager
Entity Manager
 
Dagger2 Intro
Dagger2 IntroDagger2 Intro
Dagger2 Intro
 
Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02
 
Rspec
RspecRspec
Rspec
 
Dependency injection using dagger2
Dependency injection using dagger2Dependency injection using dagger2
Dependency injection using dagger2
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
EJB Clients
EJB ClientsEJB Clients
EJB Clients
 

En vedette

Onion Architecture with S#arp
Onion Architecture with S#arpOnion Architecture with S#arp
Onion Architecture with S#arpGary Pedretti
 
TDC 2016 - Desvendando o Onion Architecture
TDC 2016 - Desvendando o Onion ArchitectureTDC 2016 - Desvendando o Onion Architecture
TDC 2016 - Desvendando o Onion ArchitectureWildtech
 
Onion network architecture
Onion network architectureOnion network architecture
Onion network architecturemahdi ataeyan
 
Onion Architecture
Onion ArchitectureOnion Architecture
Onion Architecturematthidinger
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Domain Driven Design Through Onion Architecture
Domain Driven Design Through Onion ArchitectureDomain Driven Design Through Onion Architecture
Domain Driven Design Through Onion ArchitectureBoldRadius Solutions
 

En vedette (9)

Onion architecture
Onion architectureOnion architecture
Onion architecture
 
Onion Architecture with S#arp
Onion Architecture with S#arpOnion Architecture with S#arp
Onion Architecture with S#arp
 
TDC 2016 - Desvendando o Onion Architecture
TDC 2016 - Desvendando o Onion ArchitectureTDC 2016 - Desvendando o Onion Architecture
TDC 2016 - Desvendando o Onion Architecture
 
Onion network architecture
Onion network architectureOnion network architecture
Onion network architecture
 
Onion Architecture
Onion ArchitectureOnion Architecture
Onion Architecture
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
How TOR works?
How TOR works?How TOR works?
How TOR works?
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Domain Driven Design Through Onion Architecture
Domain Driven Design Through Onion ArchitectureDomain Driven Design Through Onion Architecture
Domain Driven Design Through Onion Architecture
 

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

Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion PrincipleShahriar Hyder
 
Dependency injection and inversion
Dependency injection and inversionDependency injection and inversion
Dependency injection and inversionchhabraravish23
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
Inter Process Communication (IPC) in Android
Inter Process Communication (IPC) in AndroidInter Process Communication (IPC) in Android
Inter Process Communication (IPC) in AndroidMalwinder Singh
 
Angular.js interview questions
Angular.js interview questionsAngular.js interview questions
Angular.js interview questionscodeandyou forums
 
Sofwear deasign and need of design pattern
Sofwear deasign and need of design patternSofwear deasign and need of design pattern
Sofwear deasign and need of design patternchetankane
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkAkhil Mittal
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applicationsBabak Naffas
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design PatternRothana Choun
 
Poco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class DesignPoco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class DesignJames Phillips
 
Clean Code Part II - Dependency Injection at SoCal Code Camp
Clean Code Part II - Dependency Injection at SoCal Code CampClean Code Part II - Dependency Injection at SoCal Code Camp
Clean Code Part II - Dependency Injection at SoCal Code CampTheo Jungeblut
 
react-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryreact-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryjanet736113
 
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Cut your Dependencies with Dependency Injection for East Bay.NET User Group Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Cut your Dependencies with Dependency Injection for East Bay.NET User Group Theo Jungeblut
 
Command pattern in java
Command pattern in javaCommand pattern in java
Command pattern in javaRakibAhmed0
 
React JS Interview Question & Answer
React JS Interview Question & AnswerReact JS Interview Question & Answer
React JS Interview Question & AnswerMildain Solutions
 

Similaire à Dependency Injection або Don’t call me, I’ll call you (20)

IOC in Unity
IOC in Unity  IOC in Unity
IOC in Unity
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
 
Dependency injection and inversion
Dependency injection and inversionDependency injection and inversion
Dependency injection and inversion
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
Inter Process Communication (IPC) in Android
Inter Process Communication (IPC) in AndroidInter Process Communication (IPC) in Android
Inter Process Communication (IPC) in Android
 
Angular.js interview questions
Angular.js interview questionsAngular.js interview questions
Angular.js interview questions
 
Swiz DAO
Swiz DAOSwiz DAO
Swiz DAO
 
Sofwear deasign and need of design pattern
Sofwear deasign and need of design patternSofwear deasign and need of design pattern
Sofwear deasign and need of design pattern
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applications
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Poco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class DesignPoco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class Design
 
Clean Code Part II - Dependency Injection at SoCal Code Camp
Clean Code Part II - Dependency Injection at SoCal Code CampClean Code Part II - Dependency Injection at SoCal Code Camp
Clean Code Part II - Dependency Injection at SoCal Code Camp
 
react-slides.pdf
react-slides.pdfreact-slides.pdf
react-slides.pdf
 
react-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryreact-slides.pdf gives information about react library
react-slides.pdf gives information about react library
 
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Cut your Dependencies with Dependency Injection for East Bay.NET User Group Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
 
Command pattern in java
Command pattern in javaCommand pattern in java
Command pattern in java
 
react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
 
React JS Interview Question & Answer
React JS Interview Question & AnswerReact JS Interview Question & Answer
React JS Interview Question & Answer
 

Plus de Dmytro Mindra

Introduction to Value Planning for iHUB
Introduction to Value Planning for iHUBIntroduction to Value Planning for iHUB
Introduction to Value Planning for iHUBDmytro Mindra
 
Mastering public speaking skills
Mastering public speaking skillsMastering public speaking skills
Mastering public speaking skillsDmytro Mindra
 
XP Days Ukraine 2014 - Refactoring legacy code
XP Days Ukraine 2014 - Refactoring legacy codeXP Days Ukraine 2014 - Refactoring legacy code
XP Days Ukraine 2014 - Refactoring legacy codeDmytro Mindra
 
Odessa .NET User Group - Kinect v2
Odessa .NET User Group - Kinect v2Odessa .NET User Group - Kinect v2
Odessa .NET User Group - Kinect v2Dmytro Mindra
 
Building Windows Phone 8 Games With Unity3d
Building Windows Phone 8 Games With Unity3dBuilding Windows Phone 8 Games With Unity3d
Building Windows Phone 8 Games With Unity3dDmytro Mindra
 
IT Brunch - SpecFlow and Gherkin by Example
IT Brunch - SpecFlow and Gherkin by ExampleIT Brunch - SpecFlow and Gherkin by Example
IT Brunch - SpecFlow and Gherkin by ExampleDmytro Mindra
 
Odessa Pluralsight Study Group 28.11.2012
Odessa Pluralsight Study Group 28.11.2012Odessa Pluralsight Study Group 28.11.2012
Odessa Pluralsight Study Group 28.11.2012Dmytro Mindra
 
Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012
Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012
Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012Dmytro Mindra
 
Compilable Specifications - XPDays Ukraine 2012
Compilable Specifications - XPDays Ukraine 2012Compilable Specifications - XPDays Ukraine 2012
Compilable Specifications - XPDays Ukraine 2012Dmytro Mindra
 
NetworkUA - 2012 - Introduction TypeScript
NetworkUA - 2012 - Introduction TypeScript NetworkUA - 2012 - Introduction TypeScript
NetworkUA - 2012 - Introduction TypeScript Dmytro Mindra
 
Ciklum .NET Saturday - Introduction to TypeScript
Ciklum .NET Saturday - Introduction to TypeScriptCiklum .NET Saturday - Introduction to TypeScript
Ciklum .NET Saturday - Introduction to TypeScriptDmytro Mindra
 
Lean Lego Game for Agileee 2012
Lean Lego Game for Agileee 2012Lean Lego Game for Agileee 2012
Lean Lego Game for Agileee 2012Dmytro Mindra
 
Lohika .Net Day - What's new in Windows Azure
Lohika .Net Day - What's new in Windows AzureLohika .Net Day - What's new in Windows Azure
Lohika .Net Day - What's new in Windows AzureDmytro Mindra
 
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Dmytro Mindra
 
Windows Azure & NodeJS Microsoft SWIT 2012
Windows Azure & NodeJS Microsoft SWIT 2012 Windows Azure & NodeJS Microsoft SWIT 2012
Windows Azure & NodeJS Microsoft SWIT 2012 Dmytro Mindra
 
Lean Software Development
Lean Software DevelopmentLean Software Development
Lean Software DevelopmentDmytro Mindra
 
Craftsmanship - XP Days 2011
Craftsmanship - XP Days 2011Craftsmanship - XP Days 2011
Craftsmanship - XP Days 2011Dmytro Mindra
 
Odessa .NET User Group - 10.11.2011 - Applied Code Generation
Odessa .NET User Group - 10.11.2011 - Applied Code Generation Odessa .NET User Group - 10.11.2011 - Applied Code Generation
Odessa .NET User Group - 10.11.2011 - Applied Code Generation Dmytro Mindra
 

Plus de Dmytro Mindra (20)

Introduction to Value Planning for iHUB
Introduction to Value Planning for iHUBIntroduction to Value Planning for iHUB
Introduction to Value Planning for iHUB
 
Mastering public speaking skills
Mastering public speaking skillsMastering public speaking skills
Mastering public speaking skills
 
XP Days Ukraine 2014 - Refactoring legacy code
XP Days Ukraine 2014 - Refactoring legacy codeXP Days Ukraine 2014 - Refactoring legacy code
XP Days Ukraine 2014 - Refactoring legacy code
 
Odessa .NET User Group - Kinect v2
Odessa .NET User Group - Kinect v2Odessa .NET User Group - Kinect v2
Odessa .NET User Group - Kinect v2
 
Building Windows Phone 8 Games With Unity3d
Building Windows Phone 8 Games With Unity3dBuilding Windows Phone 8 Games With Unity3d
Building Windows Phone 8 Games With Unity3d
 
IT Brunch - SpecFlow and Gherkin by Example
IT Brunch - SpecFlow and Gherkin by ExampleIT Brunch - SpecFlow and Gherkin by Example
IT Brunch - SpecFlow and Gherkin by Example
 
Odessa Pluralsight Study Group 28.11.2012
Odessa Pluralsight Study Group 28.11.2012Odessa Pluralsight Study Group 28.11.2012
Odessa Pluralsight Study Group 28.11.2012
 
Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012
Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012
Тестируем код с Visual Studio 2012 - XP Days Ukraine 2012
 
Compilable Specifications - XPDays Ukraine 2012
Compilable Specifications - XPDays Ukraine 2012Compilable Specifications - XPDays Ukraine 2012
Compilable Specifications - XPDays Ukraine 2012
 
NetworkUA - 2012 - Introduction TypeScript
NetworkUA - 2012 - Introduction TypeScript NetworkUA - 2012 - Introduction TypeScript
NetworkUA - 2012 - Introduction TypeScript
 
Ciklum .NET Saturday - Introduction to TypeScript
Ciklum .NET Saturday - Introduction to TypeScriptCiklum .NET Saturday - Introduction to TypeScript
Ciklum .NET Saturday - Introduction to TypeScript
 
Lean Lego Game for Agileee 2012
Lean Lego Game for Agileee 2012Lean Lego Game for Agileee 2012
Lean Lego Game for Agileee 2012
 
Lohika .Net Day - What's new in Windows Azure
Lohika .Net Day - What's new in Windows AzureLohika .Net Day - What's new in Windows Azure
Lohika .Net Day - What's new in Windows Azure
 
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
 
Windows Azure & NodeJS Microsoft SWIT 2012
Windows Azure & NodeJS Microsoft SWIT 2012 Windows Azure & NodeJS Microsoft SWIT 2012
Windows Azure & NodeJS Microsoft SWIT 2012
 
Lean Software Development
Lean Software DevelopmentLean Software Development
Lean Software Development
 
Craftsmanship - XP Days 2011
Craftsmanship - XP Days 2011Craftsmanship - XP Days 2011
Craftsmanship - XP Days 2011
 
Agile architecture
Agile architectureAgile architecture
Agile architecture
 
DCI
DCIDCI
DCI
 
Odessa .NET User Group - 10.11.2011 - Applied Code Generation
Odessa .NET User Group - 10.11.2011 - Applied Code Generation Odessa .NET User Group - 10.11.2011 - Applied Code Generation
Odessa .NET User Group - 10.11.2011 - Applied Code Generation
 

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

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