SlideShare ist ein Scribd-Unternehmen logo
1 von 34
I Gotta Dependence on
Dependency Injection
November 15 2014
Matt Henroid (@mhenroid)
Senior Consultant
Daugherty Business Solutions
Agenda
• SOLID Principles
• Coupling
• Refactoring Dependencies to Abstractions
• Inversion of Control
• Dependency Injection (DI)
– Constructor Injection
– Property / setter injection
– Method injection
– Ambient Context
• Automated Testing
• Object Composition / Lifetime Management
• DI Frameworks
2
SOLID
• S – Single responsibility
– A class should have only a single responsibility
• O – Open / closed principle
– Classes should be open for extension, but closed for modification
• L – Liskov substitution principle
– Objects of a program should be replaceable with instances of their subtypes
• I – Interface segregation principle
– Many client-specific interfaces are better than one general-purpose interface
• D – Dependency inversion principle
– One should depend on abstractions and not concretions
– Not the same as Dependency Injection but related
3
The 5 commandments of OO design
ObjectA
InterfaceB InterfaceC
Method1() Method2()
ObjectB ObjectC
Method1() Method2()
Loose Coupling
ObjectA
ObjectB ObjectC
Method1() Method2()
Tight Coupling
Tight vs. Loose Coupling
4
• Coupling
– Degree to which one component (i.e. dependency) has knowledge of another
• Tight Coupling
– A class has a direct reference to a concrete class.
• Loose Coupling
– A class has a reference to an abstraction which can be implemented by one or more
classes.
ObjectA
InterfaceB InterfaceC
Method1() Method2()
ObjectD ObjectE
Method1() Method2()
Loose Coupling
ObjectA
ObjectD ObjectE
Method1() Method2()
Tight Coupling
Tight vs. Loose Coupling
5
• Benefits of Loose Coupling
– Testability – easier to test objects in isolation
– Reuse – dependencies can be swapped without modifying target
– Open / Closed Principle - change behavior without modifying target
– Parallel development – developers can work in parallel more easily
Tight Coupling Example
6
Violating Single Responsibility
Tight Coupling Example
7
How do we test
WidgetDataProvider in isolation
from its dependencies?
How can we reuse or change
WidgetDataProvider?
Refactoring Dependencies to Abstractions
• Interfaces
– Every declared method must be implemented by concrete class
• Abstract classes
– Only methods declared abstract must be implemented by concrete class
– Can provide some default implementation for methods not declared abstract
8
Refactoring Dependencies to Abstractions
• Extract interfaces from classes
9
Before After
Refactoring Dependencies to Abstractions
• Extract interfaces from classes
• Replace static classes / methods with non-static
10
Before After
Refactoring Dependencies to Abstractions
• Extract interfaces from classes
• Replace static classes / methods with non-static
• Extract non-deterministic dependencies
– Timers, Threading, DateTime dependent
11
Before After
Refactoring Dependencies to Abstractions
• Extract interfaces from classes
• Replace static classes / methods with non-static
• Extract non-deterministic dependencies
– Timers, Threading, DateTime dependent
• Replace concretions with abstractions
12
Before After
Abstraction Example
13
Inversion of Control (IoC)
• Traditional programming
– Dependencies are instantiated by a class that need them
• Inversion of Control (IoC)
– Dependencies are instantiated by a 3rd party and supplied to a class as needed
14
DependencyA DependencyB
ChildClass
IDependencyA IDependencyB
ChildClass
creates/consumes creates/consumes
ParentClass
creates/consumes
ParentClass
createsconsumes
Traditional Inversion of Control
consumesconsumes
RootContext
consumes
SomeClass creates
SomeClass
creates
SomeClass
creates
SomeClass creates
RootContext
creates/consumes
Inversion of Control (IoC)
• Dependency Injection
– Constructor Injection
– Property / Setter Injection
– Method Injection
– Ambient Context
• Factory pattern
– Dependencies created by factory class
– Factories can be injected via DI
• Service locator
– Class uses Service Locator to pull dependencies as needed
– Anti-pattern
• Hides a class’ dependencies
• Dependencies magically appear
• Great way to introduce runtime exceptions
– Caution
• Avoid using DI frameworks as Service Locator
15
Implementations
Dependency Injection
16
Constructor Injection
Use readonly fields as
backing store
Inject dependencies via
constructor
Guard against null
arguments
Save dependencies to field
• When to use
– When a dependency is required
• Important considerations
– Use single constructor
– Keep constructors lightweight
– Minimize number of dependencies (1-3)
Dependency Injection
17
Property / Setter Injection
Use public get/set to inject
dependencies.
Guard against null
references (if necessary)
• When to use
– When a dependency is optional or changeable at runtime
– When default constructor is required (ASP.NET Pages/Controls)
Dependency Injection
18
Method Injection
Dependencies passed as
parameters on every call
Guard against null
arguments
• When to use
– When a method requires different dependency for each call
Dependency Injection
19
Ambient Context
Set a default. If no default
then use NullObject pattern
Static get/set allows access
to current logger
Guard against null values
Implement concrete logger
Extract static methods to an
interface
• When to use
– Cross cutting concerns (i.e. Logging, Security, etc.)
– Avoid polluting constructors with global dependencies
• Important considerations
– Thread safety
– Use sparingly
Automated Testing
• Unit Testing
– Test a class in isolation from dependencies
– Use mock objects in place of dependencies
• Roll your own
• Framework (i.e. Moq)
– Unit tests should never interact with a database
– Should be extremely fast
• Integration Testing
– Test a class along with its dependencies
– More complex than unit tests
– May include database calls which can be slow and brittle
20
TestInitialize
21
Create fields for our mocks
and target for testing
Create mocks and inject as
needed
Create mocks and inject into
target constructor
TestMethod
22
GetWidgets() successful path
Configure our mocks to
return test data.
Use Verifiable() to ensure
that these specific methods
were called.
Execute the method we’re
testing
Verify the results are as
expected
TestMethod
23
GetWidgets() exception handling
Configure data feed to throw
an exception
Ensure exception is logged
Verify the exception is
thrown
Object Composition / Lifetime Management
• Object Composition
– How and where do we instantiate and inject dependencies?
• Object Lifetime Management
– How do we manage the lifetime of dependencies?
– How do we manage sharing dependencies?
24
Object creation
Use the data provider
Objects go out of scope and
are garbage collected.
Object Composition
• Single place in application where object graph is created
• Nearest the application entry point
• Examples
– Console App = Main method
– Windows Services = Main method
– ASP.NET Web Forms = global.asax
– ASP.NET MVC = IControllerFactory
– WCF = ServiceHostFactory
25
Composition Root
WidgetDataProvider
SqlWidgetDataFeed WidgetDataReader
Simple Object Graph
Composition Root
WidgetDataProvider
SqlWidgetDataFeed WidgetDataReader
More Realistic Object Graph
Composition
Root
Dependency Injection Frameworks
• How they make life easier
– Automatically detect and resolve dependencies (Autowiring)
– Manage object lifetime and sharing between objects (Lifetime Management)
– Allow disposing of all registered dependencies
• Lifecycle
– Register
• Perform early in application (application composition root)
• Perform all registrations at the same time
– Resolve
• Typically only resolve at the composition root
• Resolving elsewhere = Service Locator anti-pattern
– Dispose
• Dispose of DI container to ensure registered objects are disposed
• Examples
– Unity (Microsoft), Ninject, Castle Windsor, Autofac, StructureMap, …
26
Unity
Example
Create DI container
Register dependencies
Resolve root component
DI container and all
components disposed
Unity
28
Registration
• Code
– Simplest but requires recompiling when changes made
Unity
29
Registration
• Code
– Simplest but requires recompiling when changes made
• XML
– More difficult (no editor) but no recompiling when changes made
Unity
30
Registration
• Code
– Simplest but requires recompiling when changes made
• XML
– More difficult (no editor) but no recompiling when changes made
• Convention
– Good for large applications
Unity
• Transient (default)
– New instance created for each call to Resolve
• Container Controlled (i.e. singleton)
– Shared instance when Resolve or dependency injected
• Externally Controlled
– Similar to Container Controlled (i.e. singleton)
– Weak reference kept so container does not handle disposing
• Per Thread
– One instance created per thread
31
Lifetime Managers
Unity
32
Resolving
Dependency Injection Frameworks
Unity (3.0) Ninject Castle Windsor Autofac StructureMap
License MS-PL Apache 2 Apache 2 MIT Apache 2
Code Configuration Yes Yes Yes Yes Yes
XML Configuration Yes Yes Yes Yes Yes
Auto Configuration Yes Yes Yes Yes Yes
Auto Wiring Yes Yes Yes Yes Yes
Lifetime Managers Yes Yes Yes Yes Yes
Interception Yes Yes Yes Yes Yes
Constructor Injection Yes Yes Yes Yes Yes
Property Injection Yes Yes Yes Yes Yes
33
Feature Comparison
• Same basic features
• Each has advanced features that set them apart
• Be aware of performance
• Research a few before choosing
References
• Dependency Injection in .NET (Mark Seemann)
– http://techbus.safaribooksonline.com/book/programming/csharp/9781935182504
• Adaptive Code via C# (Gary McLean Hall)
– http://techbus.safaribooksonline.com/9780133979749/
• Intro to Inversion of Control (IoC)
– http://msdn.microsoft.com/en-us/library/ff921087.aspx
• Service Locator is an Anti-pattern (Mark Seemann)
– http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/
• Developer’s Guide to Dependency Injection Using Unity
– http://msdn.microsoft.com/en-us/library/dn223671(v=pandp.30).aspx
• IOC Framework Comparison
– http://blog.ashmind.com/2008/08/19/comparing-net-di-ioc-frameworks-part-1/
– http://www.palmmedia.de/blog/2011/8/30/ioc-container-benchmark-performance-
comparison
34

Weitere ähnliche Inhalte

Andere mochten auch

The art of .net deployment automation
The art of .net deployment automationThe art of .net deployment automation
The art of .net deployment automationMidVision
 
Implementing Continuous Integration in .NET for Cheapskates
Implementing Continuous Integration in .NET for CheapskatesImplementing Continuous Integration in .NET for Cheapskates
Implementing Continuous Integration in .NET for Cheapskatesmhenroid
 
The art of wmb deployment automation
The art of wmb deployment automationThe art of wmb deployment automation
The art of wmb deployment automationMidVision
 
Test driven development
Test driven developmentTest driven development
Test driven developmentShalabh Saxena
 
Agile .NET Development with BDD and Continuous Integration
Agile .NET Development with BDD and Continuous IntegrationAgile .NET Development with BDD and Continuous Integration
Agile .NET Development with BDD and Continuous IntegrationTung Nguyen Thanh
 
Domain's Robot Army
Domain's Robot ArmyDomain's Robot Army
Domain's Robot Armydomaingroup
 
Improving code quality with continuous integration (PHPBenelux Conference 2011)
Improving code quality with continuous integration (PHPBenelux Conference 2011)Improving code quality with continuous integration (PHPBenelux Conference 2011)
Improving code quality with continuous integration (PHPBenelux Conference 2011)Martin de Keijzer
 
Ideal Deployment In .NET World
Ideal Deployment In .NET WorldIdeal Deployment In .NET World
Ideal Deployment In .NET WorldDima Pasko
 
Scrum and Test-driven development
Scrum and Test-driven developmentScrum and Test-driven development
Scrum and Test-driven developmenttoteb5
 
Integration with Docker and .NET Core
Integration with Docker and .NET CoreIntegration with Docker and .NET Core
Integration with Docker and .NET CoreSriram Hariharan
 
Continuous Integration (Jenkins/Hudson)
Continuous Integration (Jenkins/Hudson)Continuous Integration (Jenkins/Hudson)
Continuous Integration (Jenkins/Hudson)Dennys Hsieh
 

Andere mochten auch (16)

The art of .net deployment automation
The art of .net deployment automationThe art of .net deployment automation
The art of .net deployment automation
 
Agile Systems Admin
Agile Systems AdminAgile Systems Admin
Agile Systems Admin
 
Implementing Continuous Integration in .NET for Cheapskates
Implementing Continuous Integration in .NET for CheapskatesImplementing Continuous Integration in .NET for Cheapskates
Implementing Continuous Integration in .NET for Cheapskates
 
The art of wmb deployment automation
The art of wmb deployment automationThe art of wmb deployment automation
The art of wmb deployment automation
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Agile .NET Development with BDD and Continuous Integration
Agile .NET Development with BDD and Continuous IntegrationAgile .NET Development with BDD and Continuous Integration
Agile .NET Development with BDD and Continuous Integration
 
Domain's Robot Army
Domain's Robot ArmyDomain's Robot Army
Domain's Robot Army
 
Buildbot
BuildbotBuildbot
Buildbot
 
Improving code quality with continuous integration (PHPBenelux Conference 2011)
Improving code quality with continuous integration (PHPBenelux Conference 2011)Improving code quality with continuous integration (PHPBenelux Conference 2011)
Improving code quality with continuous integration (PHPBenelux Conference 2011)
 
Core Principles Of Ci
Core Principles Of CiCore Principles Of Ci
Core Principles Of Ci
 
Ideal Deployment In .NET World
Ideal Deployment In .NET WorldIdeal Deployment In .NET World
Ideal Deployment In .NET World
 
Scrum and Test-driven development
Scrum and Test-driven developmentScrum and Test-driven development
Scrum and Test-driven development
 
Integration with Docker and .NET Core
Integration with Docker and .NET CoreIntegration with Docker and .NET Core
Integration with Docker and .NET Core
 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
 
Continuous Integration (Jenkins/Hudson)
Continuous Integration (Jenkins/Hudson)Continuous Integration (Jenkins/Hudson)
Continuous Integration (Jenkins/Hudson)
 
Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)
 

Ähnlich wie I gotta dependency on dependency injection

UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
Entity Framework: To the Unit of Work Design Pattern and Beyond
Entity Framework: To the Unit of Work Design Pattern and BeyondEntity Framework: To the Unit of Work Design Pattern and Beyond
Entity Framework: To the Unit of Work Design Pattern and BeyondSteve Westgarth
 
Object-oriented design principles
Object-oriented design principlesObject-oriented design principles
Object-oriented design principlesXiaoyan Chen
 
Segue to design patterns
Segue to design patternsSegue to design patterns
Segue to design patternsRahul Singh
 
Architectural Design & Patterns
Architectural Design&PatternsArchitectural Design&Patterns
Architectural Design & PatternsInocentshuja Ahmad
 
Mobile App Architectures & Coding guidelines
Mobile App Architectures & Coding guidelinesMobile App Architectures & Coding guidelines
Mobile App Architectures & Coding guidelinesQamar Abbas
 
Node.js Service - Best practices in 2019
Node.js Service - Best practices in 2019Node.js Service - Best practices in 2019
Node.js Service - Best practices in 2019Olivier Loverde
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9aminmesbahi
 
Dependency injection and inversion
Dependency injection and inversionDependency injection and inversion
Dependency injection and inversionchhabraravish23
 
Maksym Ked "Plug-In C++ Application Architecture"
Maksym Ked "Plug-In C++ Application Architecture"Maksym Ked "Plug-In C++ Application Architecture"
Maksym Ked "Plug-In C++ Application Architecture"LogeekNightUkraine
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesSteven Smith
 

Ähnlich wie I gotta dependency on dependency injection (20)

Clean architecture
Clean architectureClean architecture
Clean architecture
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Entity Framework: To the Unit of Work Design Pattern and Beyond
Entity Framework: To the Unit of Work Design Pattern and BeyondEntity Framework: To the Unit of Work Design Pattern and Beyond
Entity Framework: To the Unit of Work Design Pattern and Beyond
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Object-oriented design principles
Object-oriented design principlesObject-oriented design principles
Object-oriented design principles
 
Segue to design patterns
Segue to design patternsSegue to design patterns
Segue to design patterns
 
Architectural Design & Patterns
Architectural Design&PatternsArchitectural Design&Patterns
Architectural Design & Patterns
 
Mobile App Architectures & Coding guidelines
Mobile App Architectures & Coding guidelinesMobile App Architectures & Coding guidelines
Mobile App Architectures & Coding guidelines
 
Microservices Architecture
Microservices ArchitectureMicroservices Architecture
Microservices Architecture
 
Real-Time Design Patterns
Real-Time Design PatternsReal-Time Design Patterns
Real-Time Design Patterns
 
MVP Clean Architecture
MVP Clean  Architecture MVP Clean  Architecture
MVP Clean Architecture
 
Node.js Service - Best practices in 2019
Node.js Service - Best practices in 2019Node.js Service - Best practices in 2019
Node.js Service - Best practices in 2019
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
CNUG TDD June 2014
CNUG TDD June 2014CNUG TDD June 2014
CNUG TDD June 2014
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9
 
Dependency injection and inversion
Dependency injection and inversionDependency injection and inversion
Dependency injection and inversion
 
Maksym Ked "Plug-In C++ Application Architecture"
Maksym Ked "Plug-In C++ Application Architecture"Maksym Ked "Plug-In C++ Application Architecture"
Maksym Ked "Plug-In C++ Application Architecture"
 
Design for Testability
Design for TestabilityDesign for Testability
Design for Testability
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID Principles
 
Unit Testing in Swift
Unit Testing in SwiftUnit Testing in Swift
Unit Testing in Swift
 

Kürzlich hochgeladen

Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
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
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
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
 
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
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
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
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
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
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 

Kürzlich hochgeladen (20)

Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
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...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
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
 
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
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
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...
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
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
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 

I gotta dependency on dependency injection

  • 1. I Gotta Dependence on Dependency Injection November 15 2014 Matt Henroid (@mhenroid) Senior Consultant Daugherty Business Solutions
  • 2. Agenda • SOLID Principles • Coupling • Refactoring Dependencies to Abstractions • Inversion of Control • Dependency Injection (DI) – Constructor Injection – Property / setter injection – Method injection – Ambient Context • Automated Testing • Object Composition / Lifetime Management • DI Frameworks 2
  • 3. SOLID • S – Single responsibility – A class should have only a single responsibility • O – Open / closed principle – Classes should be open for extension, but closed for modification • L – Liskov substitution principle – Objects of a program should be replaceable with instances of their subtypes • I – Interface segregation principle – Many client-specific interfaces are better than one general-purpose interface • D – Dependency inversion principle – One should depend on abstractions and not concretions – Not the same as Dependency Injection but related 3 The 5 commandments of OO design
  • 4. ObjectA InterfaceB InterfaceC Method1() Method2() ObjectB ObjectC Method1() Method2() Loose Coupling ObjectA ObjectB ObjectC Method1() Method2() Tight Coupling Tight vs. Loose Coupling 4 • Coupling – Degree to which one component (i.e. dependency) has knowledge of another • Tight Coupling – A class has a direct reference to a concrete class. • Loose Coupling – A class has a reference to an abstraction which can be implemented by one or more classes.
  • 5. ObjectA InterfaceB InterfaceC Method1() Method2() ObjectD ObjectE Method1() Method2() Loose Coupling ObjectA ObjectD ObjectE Method1() Method2() Tight Coupling Tight vs. Loose Coupling 5 • Benefits of Loose Coupling – Testability – easier to test objects in isolation – Reuse – dependencies can be swapped without modifying target – Open / Closed Principle - change behavior without modifying target – Parallel development – developers can work in parallel more easily
  • 6. Tight Coupling Example 6 Violating Single Responsibility
  • 7. Tight Coupling Example 7 How do we test WidgetDataProvider in isolation from its dependencies? How can we reuse or change WidgetDataProvider?
  • 8. Refactoring Dependencies to Abstractions • Interfaces – Every declared method must be implemented by concrete class • Abstract classes – Only methods declared abstract must be implemented by concrete class – Can provide some default implementation for methods not declared abstract 8
  • 9. Refactoring Dependencies to Abstractions • Extract interfaces from classes 9 Before After
  • 10. Refactoring Dependencies to Abstractions • Extract interfaces from classes • Replace static classes / methods with non-static 10 Before After
  • 11. Refactoring Dependencies to Abstractions • Extract interfaces from classes • Replace static classes / methods with non-static • Extract non-deterministic dependencies – Timers, Threading, DateTime dependent 11 Before After
  • 12. Refactoring Dependencies to Abstractions • Extract interfaces from classes • Replace static classes / methods with non-static • Extract non-deterministic dependencies – Timers, Threading, DateTime dependent • Replace concretions with abstractions 12 Before After
  • 14. Inversion of Control (IoC) • Traditional programming – Dependencies are instantiated by a class that need them • Inversion of Control (IoC) – Dependencies are instantiated by a 3rd party and supplied to a class as needed 14 DependencyA DependencyB ChildClass IDependencyA IDependencyB ChildClass creates/consumes creates/consumes ParentClass creates/consumes ParentClass createsconsumes Traditional Inversion of Control consumesconsumes RootContext consumes SomeClass creates SomeClass creates SomeClass creates SomeClass creates RootContext creates/consumes
  • 15. Inversion of Control (IoC) • Dependency Injection – Constructor Injection – Property / Setter Injection – Method Injection – Ambient Context • Factory pattern – Dependencies created by factory class – Factories can be injected via DI • Service locator – Class uses Service Locator to pull dependencies as needed – Anti-pattern • Hides a class’ dependencies • Dependencies magically appear • Great way to introduce runtime exceptions – Caution • Avoid using DI frameworks as Service Locator 15 Implementations
  • 16. Dependency Injection 16 Constructor Injection Use readonly fields as backing store Inject dependencies via constructor Guard against null arguments Save dependencies to field • When to use – When a dependency is required • Important considerations – Use single constructor – Keep constructors lightweight – Minimize number of dependencies (1-3)
  • 17. Dependency Injection 17 Property / Setter Injection Use public get/set to inject dependencies. Guard against null references (if necessary) • When to use – When a dependency is optional or changeable at runtime – When default constructor is required (ASP.NET Pages/Controls)
  • 18. Dependency Injection 18 Method Injection Dependencies passed as parameters on every call Guard against null arguments • When to use – When a method requires different dependency for each call
  • 19. Dependency Injection 19 Ambient Context Set a default. If no default then use NullObject pattern Static get/set allows access to current logger Guard against null values Implement concrete logger Extract static methods to an interface • When to use – Cross cutting concerns (i.e. Logging, Security, etc.) – Avoid polluting constructors with global dependencies • Important considerations – Thread safety – Use sparingly
  • 20. Automated Testing • Unit Testing – Test a class in isolation from dependencies – Use mock objects in place of dependencies • Roll your own • Framework (i.e. Moq) – Unit tests should never interact with a database – Should be extremely fast • Integration Testing – Test a class along with its dependencies – More complex than unit tests – May include database calls which can be slow and brittle 20
  • 21. TestInitialize 21 Create fields for our mocks and target for testing Create mocks and inject as needed Create mocks and inject into target constructor
  • 22. TestMethod 22 GetWidgets() successful path Configure our mocks to return test data. Use Verifiable() to ensure that these specific methods were called. Execute the method we’re testing Verify the results are as expected
  • 23. TestMethod 23 GetWidgets() exception handling Configure data feed to throw an exception Ensure exception is logged Verify the exception is thrown
  • 24. Object Composition / Lifetime Management • Object Composition – How and where do we instantiate and inject dependencies? • Object Lifetime Management – How do we manage the lifetime of dependencies? – How do we manage sharing dependencies? 24 Object creation Use the data provider Objects go out of scope and are garbage collected.
  • 25. Object Composition • Single place in application where object graph is created • Nearest the application entry point • Examples – Console App = Main method – Windows Services = Main method – ASP.NET Web Forms = global.asax – ASP.NET MVC = IControllerFactory – WCF = ServiceHostFactory 25 Composition Root WidgetDataProvider SqlWidgetDataFeed WidgetDataReader Simple Object Graph Composition Root WidgetDataProvider SqlWidgetDataFeed WidgetDataReader More Realistic Object Graph Composition Root
  • 26. Dependency Injection Frameworks • How they make life easier – Automatically detect and resolve dependencies (Autowiring) – Manage object lifetime and sharing between objects (Lifetime Management) – Allow disposing of all registered dependencies • Lifecycle – Register • Perform early in application (application composition root) • Perform all registrations at the same time – Resolve • Typically only resolve at the composition root • Resolving elsewhere = Service Locator anti-pattern – Dispose • Dispose of DI container to ensure registered objects are disposed • Examples – Unity (Microsoft), Ninject, Castle Windsor, Autofac, StructureMap, … 26
  • 27. Unity Example Create DI container Register dependencies Resolve root component DI container and all components disposed
  • 28. Unity 28 Registration • Code – Simplest but requires recompiling when changes made
  • 29. Unity 29 Registration • Code – Simplest but requires recompiling when changes made • XML – More difficult (no editor) but no recompiling when changes made
  • 30. Unity 30 Registration • Code – Simplest but requires recompiling when changes made • XML – More difficult (no editor) but no recompiling when changes made • Convention – Good for large applications
  • 31. Unity • Transient (default) – New instance created for each call to Resolve • Container Controlled (i.e. singleton) – Shared instance when Resolve or dependency injected • Externally Controlled – Similar to Container Controlled (i.e. singleton) – Weak reference kept so container does not handle disposing • Per Thread – One instance created per thread 31 Lifetime Managers
  • 33. Dependency Injection Frameworks Unity (3.0) Ninject Castle Windsor Autofac StructureMap License MS-PL Apache 2 Apache 2 MIT Apache 2 Code Configuration Yes Yes Yes Yes Yes XML Configuration Yes Yes Yes Yes Yes Auto Configuration Yes Yes Yes Yes Yes Auto Wiring Yes Yes Yes Yes Yes Lifetime Managers Yes Yes Yes Yes Yes Interception Yes Yes Yes Yes Yes Constructor Injection Yes Yes Yes Yes Yes Property Injection Yes Yes Yes Yes Yes 33 Feature Comparison • Same basic features • Each has advanced features that set them apart • Be aware of performance • Research a few before choosing
  • 34. References • Dependency Injection in .NET (Mark Seemann) – http://techbus.safaribooksonline.com/book/programming/csharp/9781935182504 • Adaptive Code via C# (Gary McLean Hall) – http://techbus.safaribooksonline.com/9780133979749/ • Intro to Inversion of Control (IoC) – http://msdn.microsoft.com/en-us/library/ff921087.aspx • Service Locator is an Anti-pattern (Mark Seemann) – http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/ • Developer’s Guide to Dependency Injection Using Unity – http://msdn.microsoft.com/en-us/library/dn223671(v=pandp.30).aspx • IOC Framework Comparison – http://blog.ashmind.com/2008/08/19/comparing-net-di-ioc-frameworks-part-1/ – http://www.palmmedia.de/blog/2011/8/30/ioc-container-benchmark-performance- comparison 34

Hinweis der Redaktion

  1. Example of Tight Coupling Cascading effect
  2. Example of Tight Coupling Cascading effect
  3. A class can implement as many interfaces as it wants A class can only inherit from one abstract class
  4. Need way of instantiating dependencies without tight coupling.
  5. Important Considerations: Multiple constructors cause problems with DI containers Lightweight constructors keep init quick Too many dependencies code smell violating Single Responsibility Refactor to classes with SR
  6. Thread safety Multiple threads can access simultaneously Use ‘lock’ keyword to lock critical regions
  7. Example of using MSTEST which is built into Visual Studio Gets run immediately before each unit test Good place to set up our mocks and target object
  8. Each unit test has 3 parts
  9. Time to wire up to our application
  10. Where do we wire up our objects to the application?
  11. Example with Unity
  12. 3 methods for registration
  13. 3 methods for registration
  14. 3 methods for registration