SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Downloaden Sie, um offline zu lesen
Dependency Injection
Without Veils!
Agenda
• Basic Concepts
• DI under the Microscope
• DI from the Telescope
• Strategic Refactoring
• Q&A
• References
Dependency
Injection
Without Veils!
Basic Concepts
Dependencies
Dependency is a relationship between components or classes that can be
thought of as a "uses" relationship:
Class A uses Class B
or
Class B is a dependency of ClassA
Inversion of Control
Principle that promotes components that relinquish control of aspects
of the code execution to external modules or frameworks, to obtain
weak coupling. The principle can be achieved in different ways, such as
Event Driven Development, Template Method Pattern, Dependency
Injection, Asynchronous Calls, etc.
Example: The Strategy Pattern
List<T>.Sort Method (IComparer<T>)
The sort method of a List was designed to relinquish the control over
the comparison strategy to the client.
The sort method only controls the use of the comparison as a contract
operation.
The client has control over the implementation,
creation and lifetime management of IComparer dependency.
Dependency Injection
Dependency injection is a software design pattern that implements
inversion of control for resolving dependencies. A dependency is an
object that can be used (a service). An injection is the passing of a
dependency to a dependent object (a client) that would use it.
Wikipedia
Dependency Injection (DI) is a set of related patterns and principles.
It’s a way to think about and design code more than it’s a specific
technology. The ultimate purpose of using DI is to create maintainable
software within the object-oriented paradigm.
Dependency Injection in .NET,
Mark Seemann
Benefits
1. Low coupling - Easy to refactor and reuse classes
2. Plug-In architecture - Easy to replace or extend functionality
3. Late Binding - Implementation can be swapped at runtime, typically
based on configuration
4. Transparency – Explicit dependencies makes it clearer what each
component does
5. Testability – Easy to isolate dependencies and create mocks
6. Work in Parallel – contracts enable simultaneous development of
interacting components (no need to wait for dependencies to be
finished)
Under the Microscope
The DI Transformation
The Over-Controlling Messenger
Certain users want to be notified when
changes occur in any order status.
User can subscribe on the order events
that they want to receive, and the
application will sent notifications to all
interested subscribers once the event
happens.
The events available for subscription are:
The DI Transformation
Adding Transparency: explicit dependencies as parameters
The DI Transformation
Abstract Dependencies (Dependency Inversion Principle – SOLID)
The DI Transformation
Apply the Law of Demeter
The DI Transformation
Apply the Single Responsibility Principle (From SOLID)
The DI Transformation
Design by Contract
Where to inject
Constructor Injection (Best)
Used when:
• Dependencies are known at creation time
• Dependencies do not change during the object lifetime
Method Injection
Used when:
• It is preferred to reuse the same instance to reduce the # of objects
• Dependencies are used only in methods where they are injected
Property/Field Injection (Worst)
Used when:
• Dependencies are optional
Signs that you are doing it wrong…
• Too many parameters!
• Passing through parameters
• Service Locators
• Using directly stateful system dependencies
(sessions, config. Managers, etc.)
Data is not Behavior!
• Dependency on data is weak and always better
than dependency on behavior
• It is ok to create data classes (entities, data
bags, value types, structs, etc.) with the new
statement outside the injector
• Usually there is no need to abstract data
classes
From The Telescope
Building the Car App
CAR
ENGINE
TRANSMISSION
SYSTEM
ELECTIC SYSTEM AUTOBODY
TRANSMISSION
BOX
DRIVE SHAFT DIFFERENTIAL
GEAR SHIFT SHIFT ROD SHIFT FORK …
BOLT #325 BOLT #25 GEAR #890 …
START
TIME
RUNTIME
Building the Car App with DI
TRANSMISSION
BOX
DRIVE SHAFT DIFFERENTIAL
GEAR SHIFT SHIFT ROD SHIFT FORK
CAR
ENGINE
TRANSMISSION
SYSTEM
ELECTIC SYSTEM AUTOBODY
…
BOLT #325 SCREW #25 GEAR #890 …
TIME
START
INIT
I
N
J
E
C
T
O
R
Facts About The Injector
• The Injector is a factory (GoF)
• The injector has the responsibility of creating all instances in the
application and manage their lifetime.
• The Injector has helper methods containing only creational logic to
instantiate specific components. These methods are usually static.
• The helper methods can be entirely coded manually or they can rely
on frameworks called IoC Containers that can automatically resolve
dependencies based on configuration.
• The Injector methods can only be called at the top level of the code
(main, /startup/bootstrap routines) before the application starts.
• Logically we only need one injector per application, but for
maintainability purposes in large applications we may have multiple)
Injector Example
DIY
Unity
Providers
A providers is small, injectable factory class with a single method to
create a specific instance that cannot be created by the Injector during
the application startup.
Unlike Injectors, providers are intended to be injected and called at
runtime.
Example cases for using providers:
• Many instances of a class are needed
• An instance can only be created after an event (e.g. user input) has
been received
• Lazy instantiation is important (e.g. time sensitive)
The Time Provider Example
Handling Cross Cutting Concerns
Cross cutting concern components (e.g. logger, error handlers,
etc.) can pollute all constructors if used everywhere.
There are two common ways to deal with this border line
cases in DI:
• Ambient Context Pattern (DIY)
Components are referenced statically, but the static
reference is valid within a defined context and can be
changed
• Dynamic Interception (IoC Container / AOP framework)
Dynamically creates object proxies (decorators) that can
add cross cutting behavior before and/or after each method
call
Strategic Refactoring
How To: From BBoM to DI in7 Moves
1. Identify a logical area of the legacy software where bugs are reported the
most or where maintenance is painful.
2. Create integration tests for that area to ensure correct behavior
3. Devise a plan to isolate that area into a separate service through
interface/facades. Consider code duplication if there is no other way to
break out of the mess.
4. Create an injector factory and gradually apply DI (bottom up is usually
better). In the transition period, it is ok to invoke the injector in the code.
5. Write unit tests shortly before or after a component is refactored.
6. Frequently compare integration test results with the legacy code to avoid
introducing new bugs
7. Rinse and repeat
References
1. Designing Reusable Classes
http://webcache.googleusercontent.com/search?q=cache:http://www.laputan.org/drc.html
2. Inversion of Control
http://martinfowler.com/bliki/InversionOfControl.html
3. The Dependency Inversion Principle
https://drive.google.com/file/d/0BwhCYaYDn8EgMjdlMWIzNGUtZTQ0NC00ZjQ5LTkwYzQtZj
RhMDRlNTQ3ZGMz/view
4. Inversion of Control Containers and the Dependency Injection pattern
http://martinfowler.com/articles/injection.html
5. The Clean Code Talks - Don't Look For Things!
https://www.youtube.com/watch?v=RlfLCWKxHJ0
6. DIY Dependency Injection
http://blacksheep.parry.org/wp-content/uploads/2010/03/DIY-DI.pdf
7. Dependency Injection in .NET
https://www.manning.com/books/dependency-injection-in-dot-net
giovanni.scerra@afsi.com
My Contact Info:
https://www.linkedin.com/in/giovanniscerra
Thank You!
Getting Started with Unit Testing
https://www.dropbox.com/s/ivrjgk27u26r9xt/2013-09-20%2012.00%20Getting%20Started%20With%20Testing.wmv
Thoughtful Software Design
https://www.dropbox.com/s/ska44dpu1sbizwl/2015-10-27%2012.01%20Thoughtful%20Software%20Design.mp4
Other Related Presentations at AFS:

Weitere ähnliche Inhalte

Was ist angesagt?

Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency InjectionTheo Jungeblut
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web ApplicationRishi Kothari
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern11prasoon
 
Presentation On Software Testing Bug Life Cycle
Presentation On Software Testing Bug Life CyclePresentation On Software Testing Bug Life Cycle
Presentation On Software Testing Bug Life CycleRajon
 
Asp.Net Identity
Asp.Net IdentityAsp.Net Identity
Asp.Net IdentityMarwa Ahmad
 
ASP.NET Page Life Cycle
ASP.NET Page Life CycleASP.NET Page Life Cycle
ASP.NET Page Life CycleAbhishek Sur
 
.NET and C# introduction
.NET and C# introduction.NET and C# introduction
.NET and C# introductionPeter Gfader
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right wayThibaud Desodt
 
Dependency Injection in iOS
Dependency Injection in iOSDependency Injection in iOS
Dependency Injection in iOSPablo Villar
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development CodeOps Technologies LLP
 
Setting up Page Object Model in Automation Framework
Setting up Page Object Model in Automation FrameworkSetting up Page Object Model in Automation Framework
Setting up Page Object Model in Automation Frameworkvaluebound
 
Dotnet Basics Presentation
Dotnet Basics PresentationDotnet Basics Presentation
Dotnet Basics PresentationSudhakar Sharma
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionDinesh Sharma
 
Common language runtime clr
Common language runtime clrCommon language runtime clr
Common language runtime clrSanSan149
 

Was ist angesagt? (20)

Maven Introduction
Maven IntroductionMaven Introduction
Maven Introduction
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web Application
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
Presentation On Software Testing Bug Life Cycle
Presentation On Software Testing Bug Life CyclePresentation On Software Testing Bug Life Cycle
Presentation On Software Testing Bug Life Cycle
 
Asp.Net Identity
Asp.Net IdentityAsp.Net Identity
Asp.Net Identity
 
Solid principles
Solid principlesSolid principles
Solid principles
 
ASP.NET Page Life Cycle
ASP.NET Page Life CycleASP.NET Page Life Cycle
ASP.NET Page Life Cycle
 
.NET and C# introduction
.NET and C# introduction.NET and C# introduction
.NET and C# introduction
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Junit
JunitJunit
Junit
 
C sharp
C sharpC sharp
C sharp
 
Dependency Injection in iOS
Dependency Injection in iOSDependency Injection in iOS
Dependency Injection in iOS
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
 
Code review
Code reviewCode review
Code review
 
Setting up Page Object Model in Automation Framework
Setting up Page Object Model in Automation FrameworkSetting up Page Object Model in Automation Framework
Setting up Page Object Model in Automation Framework
 
Dotnet Basics Presentation
Dotnet Basics PresentationDotnet Basics Presentation
Dotnet Basics Presentation
 
Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency Injection
 
Common language runtime clr
Common language runtime clrCommon language runtime clr
Common language runtime clr
 

Ähnlich wie Dependency Injection

Large scale enterprise software architecture
Large scale enterprise software architectureLarge scale enterprise software architecture
Large scale enterprise software architectureMohammad Yeganehfar
 
Component based development | what, why and how
Component based development | what, why and howComponent based development | what, why and how
Component based development | what, why and howRakesh Kumar Jha
 
King Tut Architecture
King Tut ArchitectureKing Tut Architecture
King Tut ArchitectureGary Pedretti
 
Software archiecture lecture08
Software archiecture   lecture08Software archiecture   lecture08
Software archiecture lecture08Luktalja
 
Porting the Legacy Application to Composite Application Guidance
Porting the Legacy Application to Composite Application GuidancePorting the Legacy Application to Composite Application Guidance
Porting the Legacy Application to Composite Application GuidanceOur Community Exchange LLC
 
Test Driven Development:Unit Testing, Dependency Injection, Mocking
Test Driven Development:Unit Testing, Dependency Injection, MockingTest Driven Development:Unit Testing, Dependency Injection, Mocking
Test Driven Development:Unit Testing, Dependency Injection, Mockingmrjawright
 
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
 
Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast trackBinu Bhasuran
 
Dependency injection and inversion
Dependency injection and inversionDependency injection and inversion
Dependency injection and inversionchhabraravish23
 
SOLID Design Principles for Test Automaion
SOLID Design Principles for Test AutomaionSOLID Design Principles for Test Automaion
SOLID Design Principles for Test AutomaionKnoldus Inc.
 
Mobile App Architectures & Coding guidelines
Mobile App Architectures & Coding guidelinesMobile App Architectures & Coding guidelines
Mobile App Architectures & Coding guidelinesQamar Abbas
 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckCut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckTheo Jungeblut
 
Infrastructure as Code with Ansible
Infrastructure as Code with AnsibleInfrastructure as Code with Ansible
Infrastructure as Code with AnsibleDaniel Bezerra
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NETssusere19c741
 
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Cut your Dependencies - Dependency Injection at Silicon Valley Code CampCut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Cut your Dependencies - Dependency Injection at Silicon Valley Code CampTheo Jungeblut
 
PayPal Resilient System Design
PayPal Resilient System DesignPayPal Resilient System Design
PayPal Resilient System DesignPradeep Ballal
 
Over view of software artitecture
Over view of software artitectureOver view of software artitecture
Over view of software artitectureABDEL RAHMAN KARIM
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to SpringSujit Kumar
 

Ähnlich wie Dependency Injection (20)

Large scale enterprise software architecture
Large scale enterprise software architectureLarge scale enterprise software architecture
Large scale enterprise software architecture
 
Component based development | what, why and how
Component based development | what, why and howComponent based development | what, why and how
Component based development | what, why and how
 
Xp conf-tbd
Xp conf-tbdXp conf-tbd
Xp conf-tbd
 
King Tut Architecture
King Tut ArchitectureKing Tut Architecture
King Tut Architecture
 
Coding
CodingCoding
Coding
 
Software archiecture lecture08
Software archiecture   lecture08Software archiecture   lecture08
Software archiecture lecture08
 
Porting the Legacy Application to Composite Application Guidance
Porting the Legacy Application to Composite Application GuidancePorting the Legacy Application to Composite Application Guidance
Porting the Legacy Application to Composite Application Guidance
 
Test Driven Development:Unit Testing, Dependency Injection, Mocking
Test Driven Development:Unit Testing, Dependency Injection, MockingTest Driven Development:Unit Testing, Dependency Injection, Mocking
Test Driven Development:Unit Testing, Dependency Injection, Mocking
 
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
 
Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast track
 
Dependency injection and inversion
Dependency injection and inversionDependency injection and inversion
Dependency injection and inversion
 
SOLID Design Principles for Test Automaion
SOLID Design Principles for Test AutomaionSOLID Design Principles for Test Automaion
SOLID Design Principles for Test Automaion
 
Mobile App Architectures & Coding guidelines
Mobile App Architectures & Coding guidelinesMobile App Architectures & Coding guidelines
Mobile App Architectures & Coding guidelines
 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckCut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
 
Infrastructure as Code with Ansible
Infrastructure as Code with AnsibleInfrastructure as Code with Ansible
Infrastructure as Code with Ansible
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NET
 
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Cut your Dependencies - Dependency Injection at Silicon Valley Code CampCut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
 
PayPal Resilient System Design
PayPal Resilient System DesignPayPal Resilient System Design
PayPal Resilient System Design
 
Over view of software artitecture
Over view of software artitectureOver view of software artitecture
Over view of software artitecture
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to Spring
 

Mehr von Giovanni Scerra ☃

Mehr von Giovanni Scerra ☃ (6)

Getting Started With QA Automation
Getting Started With QA AutomationGetting Started With QA Automation
Getting Started With QA Automation
 
Thoughtful Software Design
Thoughtful Software DesignThoughtful Software Design
Thoughtful Software Design
 
Improving Estimates
Improving EstimatesImproving Estimates
Improving Estimates
 
Getting Started With Testing
Getting Started With TestingGetting Started With Testing
Getting Started With Testing
 
Unit Testing SQL Server
Unit Testing SQL ServerUnit Testing SQL Server
Unit Testing SQL Server
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 

Kürzlich hochgeladen

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 

Kürzlich hochgeladen (20)

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 

Dependency Injection

  • 2. Agenda • Basic Concepts • DI under the Microscope • DI from the Telescope • Strategic Refactoring • Q&A • References Dependency Injection Without Veils!
  • 4. Dependencies Dependency is a relationship between components or classes that can be thought of as a "uses" relationship: Class A uses Class B or Class B is a dependency of ClassA
  • 5. Inversion of Control Principle that promotes components that relinquish control of aspects of the code execution to external modules or frameworks, to obtain weak coupling. The principle can be achieved in different ways, such as Event Driven Development, Template Method Pattern, Dependency Injection, Asynchronous Calls, etc. Example: The Strategy Pattern List<T>.Sort Method (IComparer<T>) The sort method of a List was designed to relinquish the control over the comparison strategy to the client. The sort method only controls the use of the comparison as a contract operation. The client has control over the implementation, creation and lifetime management of IComparer dependency.
  • 6. Dependency Injection Dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. Wikipedia Dependency Injection (DI) is a set of related patterns and principles. It’s a way to think about and design code more than it’s a specific technology. The ultimate purpose of using DI is to create maintainable software within the object-oriented paradigm. Dependency Injection in .NET, Mark Seemann
  • 7. Benefits 1. Low coupling - Easy to refactor and reuse classes 2. Plug-In architecture - Easy to replace or extend functionality 3. Late Binding - Implementation can be swapped at runtime, typically based on configuration 4. Transparency – Explicit dependencies makes it clearer what each component does 5. Testability – Easy to isolate dependencies and create mocks 6. Work in Parallel – contracts enable simultaneous development of interacting components (no need to wait for dependencies to be finished)
  • 9. The DI Transformation The Over-Controlling Messenger Certain users want to be notified when changes occur in any order status. User can subscribe on the order events that they want to receive, and the application will sent notifications to all interested subscribers once the event happens. The events available for subscription are:
  • 10. The DI Transformation Adding Transparency: explicit dependencies as parameters
  • 11. The DI Transformation Abstract Dependencies (Dependency Inversion Principle – SOLID)
  • 12. The DI Transformation Apply the Law of Demeter
  • 13. The DI Transformation Apply the Single Responsibility Principle (From SOLID)
  • 15. Where to inject Constructor Injection (Best) Used when: • Dependencies are known at creation time • Dependencies do not change during the object lifetime Method Injection Used when: • It is preferred to reuse the same instance to reduce the # of objects • Dependencies are used only in methods where they are injected Property/Field Injection (Worst) Used when: • Dependencies are optional
  • 16. Signs that you are doing it wrong… • Too many parameters! • Passing through parameters • Service Locators • Using directly stateful system dependencies (sessions, config. Managers, etc.)
  • 17. Data is not Behavior! • Dependency on data is weak and always better than dependency on behavior • It is ok to create data classes (entities, data bags, value types, structs, etc.) with the new statement outside the injector • Usually there is no need to abstract data classes
  • 19. Building the Car App CAR ENGINE TRANSMISSION SYSTEM ELECTIC SYSTEM AUTOBODY TRANSMISSION BOX DRIVE SHAFT DIFFERENTIAL GEAR SHIFT SHIFT ROD SHIFT FORK … BOLT #325 BOLT #25 GEAR #890 … START TIME RUNTIME
  • 20. Building the Car App with DI TRANSMISSION BOX DRIVE SHAFT DIFFERENTIAL GEAR SHIFT SHIFT ROD SHIFT FORK CAR ENGINE TRANSMISSION SYSTEM ELECTIC SYSTEM AUTOBODY … BOLT #325 SCREW #25 GEAR #890 … TIME START INIT I N J E C T O R
  • 21. Facts About The Injector • The Injector is a factory (GoF) • The injector has the responsibility of creating all instances in the application and manage their lifetime. • The Injector has helper methods containing only creational logic to instantiate specific components. These methods are usually static. • The helper methods can be entirely coded manually or they can rely on frameworks called IoC Containers that can automatically resolve dependencies based on configuration. • The Injector methods can only be called at the top level of the code (main, /startup/bootstrap routines) before the application starts. • Logically we only need one injector per application, but for maintainability purposes in large applications we may have multiple)
  • 23. Providers A providers is small, injectable factory class with a single method to create a specific instance that cannot be created by the Injector during the application startup. Unlike Injectors, providers are intended to be injected and called at runtime. Example cases for using providers: • Many instances of a class are needed • An instance can only be created after an event (e.g. user input) has been received • Lazy instantiation is important (e.g. time sensitive)
  • 24. The Time Provider Example
  • 25. Handling Cross Cutting Concerns Cross cutting concern components (e.g. logger, error handlers, etc.) can pollute all constructors if used everywhere. There are two common ways to deal with this border line cases in DI: • Ambient Context Pattern (DIY) Components are referenced statically, but the static reference is valid within a defined context and can be changed • Dynamic Interception (IoC Container / AOP framework) Dynamically creates object proxies (decorators) that can add cross cutting behavior before and/or after each method call
  • 27. How To: From BBoM to DI in7 Moves 1. Identify a logical area of the legacy software where bugs are reported the most or where maintenance is painful. 2. Create integration tests for that area to ensure correct behavior 3. Devise a plan to isolate that area into a separate service through interface/facades. Consider code duplication if there is no other way to break out of the mess. 4. Create an injector factory and gradually apply DI (bottom up is usually better). In the transition period, it is ok to invoke the injector in the code. 5. Write unit tests shortly before or after a component is refactored. 6. Frequently compare integration test results with the legacy code to avoid introducing new bugs 7. Rinse and repeat
  • 28. References 1. Designing Reusable Classes http://webcache.googleusercontent.com/search?q=cache:http://www.laputan.org/drc.html 2. Inversion of Control http://martinfowler.com/bliki/InversionOfControl.html 3. The Dependency Inversion Principle https://drive.google.com/file/d/0BwhCYaYDn8EgMjdlMWIzNGUtZTQ0NC00ZjQ5LTkwYzQtZj RhMDRlNTQ3ZGMz/view 4. Inversion of Control Containers and the Dependency Injection pattern http://martinfowler.com/articles/injection.html 5. The Clean Code Talks - Don't Look For Things! https://www.youtube.com/watch?v=RlfLCWKxHJ0 6. DIY Dependency Injection http://blacksheep.parry.org/wp-content/uploads/2010/03/DIY-DI.pdf 7. Dependency Injection in .NET https://www.manning.com/books/dependency-injection-in-dot-net
  • 29. giovanni.scerra@afsi.com My Contact Info: https://www.linkedin.com/in/giovanniscerra Thank You! Getting Started with Unit Testing https://www.dropbox.com/s/ivrjgk27u26r9xt/2013-09-20%2012.00%20Getting%20Started%20With%20Testing.wmv Thoughtful Software Design https://www.dropbox.com/s/ska44dpu1sbizwl/2015-10-27%2012.01%20Thoughtful%20Software%20Design.mp4 Other Related Presentations at AFS: