SlideShare une entreprise Scribd logo
1  sur  23
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
Dependency Injection and Inversion
of Control
Developing flexible, reusable and testable software
Moslem Rashidi
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
Something about the author
• This pattern was introduced in 2004 by Martin Fowler
• Martin Fowler is an author and
international speaker on software
development, specializing in object-oriented 
analysis and design, UML, patterns and
agile software development.
• In March 2000, he became Chief Scientist at ThoughtWorks, a systems
integration and consulting company.
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
Intent
Intent of Dependency injection pattern:
It refers to the process of supplying an
external dependency to a software
component
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
What is a “Dependency”?
Some common dependencies include:
• Application Layers
– Data Access Layer & Databases
– Business Layer
• External services & Components
– Web Services
– Third Party Components
• Framework Components
– File Objects (File.Delete(…), Directory.Exists(…))
– Web Objects (HttpContext, Session, Request, etc)
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
Loosely Coupled Systems
• Good OO Systems – organised as web of interacting objects
• Goal – High cohesion, low coupling
• Advantages of low coupling
– Extensibility
– Testability
– Reusability
• Not so easy to achieve!
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
A Concrete Example – A Trade Monitor
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
Trade Monitor – The design
• TradeMonitor is coupled to LimitDao – this is not good!
– Extensibility – what if not database but distributed cache
– Testability – where do the limits for test come from?
– Reusability – logic is fairly generic . . .
public class TradeMonitor
{
private LimitDao limitDao;
public TradeMonitor()
{
limitDao = new LimitDao();
}
public bool TryTrade(string symbol, int amount)
{
int limit = limitDao.GetLimit(symbol);
int exposure = limitDao.GetExposure(symbol);
return (exposure + amount > limit) ? false : true;
}
}
public class LimitDao
{
public int GetExposure(string symbol)
{
// Do something with the database
}
public int GetLimit(string sysmbol)
{
// Do something with the database
}
}
limitDao = new LimitDao();
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
Trade Monitor – The Design Refactored (1)
• Introduce interface/implementation separation
– Logic does not depend on DAO anymore.
– Does this really solve the problem?
public class TradeMonitor
{
private ILimitRepository limitRepository;
public TradeMonitor()
{
limitRepository = new LimitDao();
}
public bool TryTrade(string symbol, int amount)
{
. . .
}
}
public interface ILimitRepository
{
int GetExposure(string symbol);
int GetLimit(string symbol);
}
limitRepository = new LimitDao();
• The constructor still has a static dependency on DAO
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
Trade Monitor – The Design Refactored (2)
• Introduce Factory
• TradeMonitor decoupled from LimitDao
public class LimitFactory
{
public static ILimitRepository GetLimitRepository()
{
return new LimitDao();
}
}
public class TradeMonitor
{
private ILimitRepository limitRepository;
public TradeMonitor()
{
limitRepository = LimitFactory.GetLimitRepository();
}
public bool TryTrade(string symbol, int amount)
{
. . .
}
}
LimitFactory
TradeMonitor
<<interface>>
LimitRepository
LimitDao
<<creates>>
return new LimitDao();
• LimitDao still tightly-coupled albeit to Factory
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
Trade Monitor – The Design Refactored (3)
• Introduce ServiceLocator
• This gives us extensibility, testability, reusability
public class ServiceLocator
{
public static void RegisterService(Type type, object impl)
{. . .}
public static object GetService(Type type)
{. . .}
}
public class TradeMonitor
{
private ILimitRepository limitRepository;
public TradeMonitor()
{
object o =
ServiceLocator.GetService(typeof(ILimitRepository));
limitRepository = o as ILimitRepository;
}
public bool TryTrade(string symbol, int amount)
{
. . .
}
}
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
ServiceLocator - Problems
• Sequence dependence
• Cumbersome setup in tests
• Service depends on infrastructure code, (ServiceLocator)
• Code needs to handle lookup problems
• Aren’t these problem minor?
Why settle for something we know has issues?
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
A Different View
• What about adding a setter and let something else worry about creation
and resolution?
public class TradeMonitor
{
private ILimitRepository limitRepository;
public TradeMonitor()
{
}
public ILimitRepository Limits
{
set { limitRepository = value;}
}
}
• The dependencies are injected from the outside
• Components are passive and are not concerned with locating or
creating dependencies
This is Setter Dependency Injection
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
Another Idea
• Why not just use the constructor?
public class TradeMonitor
{
private ILimitRepository limitRepository;
public TradeMonitor(ILimitRepository limitRepository)
{
this.limitRepository = limitRepository;
}
}
• No setters for dependent components, (obviously)
• One-shot initialisation – components are always initialised correctly
• All dependencies are clearly visible from code
• It is impossible to create cyclic dependencies
This is Constructor Dependency
Injection
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
What about Inversion of Control?
• Dependency Injection - one example of IoC design principle.
• Also known as the Hollywood Principle
– Don’t call us, we’ll call you!
• Objects rely on their environment to provide dependencies rather than
actively obtaining them.
• Inversion of Control can make the difference between a library and a
framework.
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
IoC Containers
• There are still some open questions
– Who creates the dependencies?
– What if we need some initialisation code that must be run after
dependencies have been set?
– What happens when we don’t have all the components?
• IoC Containers solve these issues
– Have configuration – often external
– Create objects
– Ensure all dependencies are satisfied
– Provide lifecycle support
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
It Gets Better
• We can use reflection to determine dependencies – no need for config
files.
• Most IoC containers support auto-wiring.
• Make components known to container.
• Container examines constructors and determines dependencies.
• Auto-wiring provides other benefits.
• Less typing, especially long assembly names.
• Static type checking by IDE at edit time.
• More intuitive for developer.
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
IoC Containers and Features
Container Setter
DI
Ctor
DI
External
config
Code
config
Auto-
wiring
Lifecycle
support`
Url
System.ComponentModel a a Part of .Net framework
PicoContainer.Net a a a a a http://picocontainer.org
Windsor a a a ? a http://www.castleproject.org
StructureMap a a a P a http://sourceforge.net/projects/structuremap
Spring.Net a a a ? a a http://www.springframework.net/
ObjectBuilder a a a a ?? a http://msdn.microsoft.com
?? = More investigation
? = Setter based DI required for primitive dependencies
P = Partial still requires configuration to point to assemblies to scan
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
The Solution – Test Case
[TestFixture]
public class TradeMonitorTest
{
[Test]
public void MonitorBlocksTradesWhenLimitExceeded()
{
DynamicMock mockRepository = new DynamicMock(typeof(ILimitRepository));
mockRepository.SetupResult('GetLimit', 1000000, new Type[] { typeof(string) });
mockRepository.SetupResult('GetExposure', 999999, new Type[] { typeof(string) });
TradeMonitor monitor = new TradeMonitor((ILimitRepository)mockRepository.MockInstance);
Assert.IsFalse(monitor.TryTrade('MSFT', 1000), 'Monitor should block trade');
}
}
public class TradeMonitor
{
private ILimitRepository repository;
public TradeMonitor(ILimitRepository repository) { this.repository = repository; }
public bool TryTrade(string symbol, int amount)
{
int limit = repository.GetLimit(symbol);
int exposure = repository.GetExposure(symbol);
return ((amount + exposure) <= limit);
}
}
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
The Solution – Using the Windsor Container
• Code configuration
IWindsorContainer container = new WindsorContainer();
container.AddComponent('limitRepository', typeof(ILimitRepository), typeof(LimitDao));
container.AddComponent('tradeMonitor', typeof(TradeMonitor));
TradeMonitor monitor = (TradeMonitor)container['tradeMonitor'];
monitor.TryTrade('MSFT', 1000);
• External configuration
IWindsorContainer container = new WindsorContainer('config.xml');
TradeMonitor monitor = (TradeMonitor)container['tradeMonitor'];
monitor.TryTrade('MSFT', 1000);
<configuration>
<components>
<component id='limitRepository' service='AAABank.ILimitRepository, AAABank'
type='AAABank.LimitDao, AAABank' />
<component id='tradeMonitor' type='AAABank.TradeMonitor, AAABank' />
</components>
</configuration>
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
The Solution – Complex Configuration
• What if components take parameters?
public class LimitDao
{
public LimitDao(string connectionString) {…}
}
public class TradeMonitor
{
public TradeMonitor(string[] monitoredSymbols) {…}
}
<configuration>
<components>
<component id='limitRepository' service='AAABank.ILimitRepository, AAABank'
type='AAABank.LimitDao, AAABank'>
<connectionString>Data Source=AServer;Initial Catalog=BankDB;User ID=sa</connectionString>
</component>
. . .
<configuration>
<components>
<component id='tradeMonitor' type='AAABank.TradeMonitor, AAABank'>
<monitoredSymbols>
<array>
<elem>MSFT</elem>
<elem>TWUK</elem>
</array>
</monitoredSymbols>
. . .
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
Many other possibilities
• Container creates objects – but what objects?
• Can return proxy – no need for MarshalByRef inheritance.
• Object instance caching.
• Aspect Oriented Programming (concerns ,advice ,join point, pointcut).
• Remoting by configuration.
• Automatic Web Service creation.
• . . .
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
Summary
• Container based DI facilitates: -
– Testability
– Extensibility
– Reusability
• Makes the difference between framework and library
– Not just use but extend
• Essential for complex Domain Driven Design
– Easier to separate 'infrastructure' from business logic
Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011
Questions?

Contenu connexe

Tendances

Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisMahesh Bhalerao
 
The 5 principles of Model Based Systems Engineering (MBSE)
The 5 principles of Model Based Systems Engineering (MBSE)The 5 principles of Model Based Systems Engineering (MBSE)
The 5 principles of Model Based Systems Engineering (MBSE)James Towers
 
SOLID Software Principles with C#
SOLID Software Principles with C#SOLID Software Principles with C#
SOLID Software Principles with C#Ken Burkhardt
 
Aspect Oriented Programming Through C#.NET
Aspect Oriented Programming Through C#.NETAspect Oriented Programming Through C#.NET
Aspect Oriented Programming Through C#.NETWaqas Tariq
 
Design patterns in android
Design patterns in androidDesign patterns in android
Design patterns in androidZahra Heydari
 
Creational pattern
Creational patternCreational pattern
Creational patternHimanshu
 
Bartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsBartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsJason Townsend, MBA
 
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
 
.NET Architecture for Enterprises
.NET Architecture for Enterprises.NET Architecture for Enterprises
.NET Architecture for EnterprisesWade Wegner
 
Gof design pattern
Gof design patternGof design pattern
Gof design patternnaveen kumar
 
Agile Open 2009 Tdd And Architecture Influences
Agile Open 2009   Tdd And Architecture InfluencesAgile Open 2009   Tdd And Architecture Influences
Agile Open 2009 Tdd And Architecture InfluencesGustavo Andres Brey
 
Object Oriented Design Principles
Object Oriented Design PrinciplesObject Oriented Design Principles
Object Oriented Design PrinciplesThang Tran Duc
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with javaRajiv Gupta
 
Java Design Pattern Interview Questions
Java Design Pattern Interview QuestionsJava Design Pattern Interview Questions
Java Design Pattern Interview Questionsjbashask
 
Design patterns creational patterns
Design patterns creational patternsDesign patterns creational patterns
Design patterns creational patternsMalik Sajid
 
ASPECT ORIENTED PROGRAMING(aop)
ASPECT ORIENTED PROGRAMING(aop)ASPECT ORIENTED PROGRAMING(aop)
ASPECT ORIENTED PROGRAMING(aop)kvsrteja
 

Tendances (20)

Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Spring survey
Spring surveySpring survey
Spring survey
 
The 5 principles of Model Based Systems Engineering (MBSE)
The 5 principles of Model Based Systems Engineering (MBSE)The 5 principles of Model Based Systems Engineering (MBSE)
The 5 principles of Model Based Systems Engineering (MBSE)
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
SOLID Software Principles with C#
SOLID Software Principles with C#SOLID Software Principles with C#
SOLID Software Principles with C#
 
Aspect Oriented Programming Through C#.NET
Aspect Oriented Programming Through C#.NETAspect Oriented Programming Through C#.NET
Aspect Oriented Programming Through C#.NET
 
Design patterns in android
Design patterns in androidDesign patterns in android
Design patterns in android
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Bartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsBartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design Patterns
 
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
 
.NET Architecture for Enterprises
.NET Architecture for Enterprises.NET Architecture for Enterprises
.NET Architecture for Enterprises
 
Gof design pattern
Gof design patternGof design pattern
Gof design pattern
 
Agile Open 2009 Tdd And Architecture Influences
Agile Open 2009   Tdd And Architecture InfluencesAgile Open 2009   Tdd And Architecture Influences
Agile Open 2009 Tdd And Architecture Influences
 
Patterns for distributed systems
Patterns for distributed systemsPatterns for distributed systems
Patterns for distributed systems
 
Object Oriented Design Principles
Object Oriented Design PrinciplesObject Oriented Design Principles
Object Oriented Design Principles
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with java
 
Sda 8
Sda   8Sda   8
Sda 8
 
Java Design Pattern Interview Questions
Java Design Pattern Interview QuestionsJava Design Pattern Interview Questions
Java Design Pattern Interview Questions
 
Design patterns creational patterns
Design patterns creational patternsDesign patterns creational patterns
Design patterns creational patterns
 
ASPECT ORIENTED PROGRAMING(aop)
ASPECT ORIENTED PROGRAMING(aop)ASPECT ORIENTED PROGRAMING(aop)
ASPECT ORIENTED PROGRAMING(aop)
 

Similaire à Inversion of control

springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfBruceLee275640
 
Elements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstElements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstEnea Gabriel
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2Hammad Rajjoub
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency InjectionTheo Jungeblut
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Spring 1 day program
Spring 1 day programSpring 1 day program
Spring 1 day programMohit Kanwar
 
Architecting modern Android apps
Architecting modern Android appsArchitecting modern Android apps
Architecting modern Android appsGrigori Hlopkov
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Steven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
Dependency Injection & IoC
Dependency Injection & IoCDependency Injection & IoC
Dependency Injection & IoCDennis Loktionov
 
Reference Architecture
Reference ArchitectureReference Architecture
Reference ArchitectureJohan Eltes
 
Constructing Enterprise Applications
Constructing Enterprise  ApplicationsConstructing Enterprise  Applications
Constructing Enterprise ApplicationsGem WeBlog
 
The differing ways to monitor and instrument
The differing ways to monitor and instrumentThe differing ways to monitor and instrument
The differing ways to monitor and instrumentJonah Kowall
 
The Magic Of Application Lifecycle Management In Vs Public
The Magic Of Application Lifecycle Management In Vs PublicThe Magic Of Application Lifecycle Management In Vs Public
The Magic Of Application Lifecycle Management In Vs PublicDavid Solivan
 
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
 
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
 

Similaire à Inversion of control (20)

springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdf
 
Top Testing Tips
Top Testing TipsTop Testing Tips
Top Testing Tips
 
Elements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstElements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code First
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2C:\Fakepath\Combating Software Entropy 2
C:\Fakepath\Combating Software Entropy 2
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
soa1.ppt
soa1.pptsoa1.ppt
soa1.ppt
 
Spring 1 day program
Spring 1 day programSpring 1 day program
Spring 1 day program
 
Architecting modern Android apps
Architecting modern Android appsArchitecting modern Android apps
Architecting modern Android apps
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Ladc presentation
Ladc presentationLadc presentation
Ladc presentation
 
Dependency Injection & IoC
Dependency Injection & IoCDependency Injection & IoC
Dependency Injection & IoC
 
Reference Architecture
Reference ArchitectureReference Architecture
Reference Architecture
 
Constructing Enterprise Applications
Constructing Enterprise  ApplicationsConstructing Enterprise  Applications
Constructing Enterprise Applications
 
The differing ways to monitor and instrument
The differing ways to monitor and instrumentThe differing ways to monitor and instrument
The differing ways to monitor and instrument
 
The Magic Of Application Lifecycle Management In Vs Public
The Magic Of Application Lifecycle Management In Vs PublicThe Magic Of Application Lifecycle Management In Vs Public
The Magic Of Application Lifecycle Management In Vs Public
 
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
 
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
 

Dernier

Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 

Dernier (20)

Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 

Inversion of control

  • 1. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 Dependency Injection and Inversion of Control Developing flexible, reusable and testable software Moslem Rashidi
  • 2. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 Something about the author • This pattern was introduced in 2004 by Martin Fowler • Martin Fowler is an author and international speaker on software development, specializing in object-oriented  analysis and design, UML, patterns and agile software development. • In March 2000, he became Chief Scientist at ThoughtWorks, a systems integration and consulting company.
  • 3. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 Intent Intent of Dependency injection pattern: It refers to the process of supplying an external dependency to a software component
  • 4. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 What is a “Dependency”? Some common dependencies include: • Application Layers – Data Access Layer & Databases – Business Layer • External services & Components – Web Services – Third Party Components • Framework Components – File Objects (File.Delete(…), Directory.Exists(…)) – Web Objects (HttpContext, Session, Request, etc)
  • 5. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 Loosely Coupled Systems • Good OO Systems – organised as web of interacting objects • Goal – High cohesion, low coupling • Advantages of low coupling – Extensibility – Testability – Reusability • Not so easy to achieve!
  • 6. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 A Concrete Example – A Trade Monitor
  • 7. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 Trade Monitor – The design • TradeMonitor is coupled to LimitDao – this is not good! – Extensibility – what if not database but distributed cache – Testability – where do the limits for test come from? – Reusability – logic is fairly generic . . . public class TradeMonitor { private LimitDao limitDao; public TradeMonitor() { limitDao = new LimitDao(); } public bool TryTrade(string symbol, int amount) { int limit = limitDao.GetLimit(symbol); int exposure = limitDao.GetExposure(symbol); return (exposure + amount > limit) ? false : true; } } public class LimitDao { public int GetExposure(string symbol) { // Do something with the database } public int GetLimit(string sysmbol) { // Do something with the database } } limitDao = new LimitDao();
  • 8. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 Trade Monitor – The Design Refactored (1) • Introduce interface/implementation separation – Logic does not depend on DAO anymore. – Does this really solve the problem? public class TradeMonitor { private ILimitRepository limitRepository; public TradeMonitor() { limitRepository = new LimitDao(); } public bool TryTrade(string symbol, int amount) { . . . } } public interface ILimitRepository { int GetExposure(string symbol); int GetLimit(string symbol); } limitRepository = new LimitDao(); • The constructor still has a static dependency on DAO
  • 9. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 Trade Monitor – The Design Refactored (2) • Introduce Factory • TradeMonitor decoupled from LimitDao public class LimitFactory { public static ILimitRepository GetLimitRepository() { return new LimitDao(); } } public class TradeMonitor { private ILimitRepository limitRepository; public TradeMonitor() { limitRepository = LimitFactory.GetLimitRepository(); } public bool TryTrade(string symbol, int amount) { . . . } } LimitFactory TradeMonitor <<interface>> LimitRepository LimitDao <<creates>> return new LimitDao(); • LimitDao still tightly-coupled albeit to Factory
  • 10. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 Trade Monitor – The Design Refactored (3) • Introduce ServiceLocator • This gives us extensibility, testability, reusability public class ServiceLocator { public static void RegisterService(Type type, object impl) {. . .} public static object GetService(Type type) {. . .} } public class TradeMonitor { private ILimitRepository limitRepository; public TradeMonitor() { object o = ServiceLocator.GetService(typeof(ILimitRepository)); limitRepository = o as ILimitRepository; } public bool TryTrade(string symbol, int amount) { . . . } }
  • 11. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 ServiceLocator - Problems • Sequence dependence • Cumbersome setup in tests • Service depends on infrastructure code, (ServiceLocator) • Code needs to handle lookup problems • Aren’t these problem minor? Why settle for something we know has issues?
  • 12. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 A Different View • What about adding a setter and let something else worry about creation and resolution? public class TradeMonitor { private ILimitRepository limitRepository; public TradeMonitor() { } public ILimitRepository Limits { set { limitRepository = value;} } } • The dependencies are injected from the outside • Components are passive and are not concerned with locating or creating dependencies This is Setter Dependency Injection
  • 13. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 Another Idea • Why not just use the constructor? public class TradeMonitor { private ILimitRepository limitRepository; public TradeMonitor(ILimitRepository limitRepository) { this.limitRepository = limitRepository; } } • No setters for dependent components, (obviously) • One-shot initialisation – components are always initialised correctly • All dependencies are clearly visible from code • It is impossible to create cyclic dependencies This is Constructor Dependency Injection
  • 14. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 What about Inversion of Control? • Dependency Injection - one example of IoC design principle. • Also known as the Hollywood Principle – Don’t call us, we’ll call you! • Objects rely on their environment to provide dependencies rather than actively obtaining them. • Inversion of Control can make the difference between a library and a framework.
  • 15. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 IoC Containers • There are still some open questions – Who creates the dependencies? – What if we need some initialisation code that must be run after dependencies have been set? – What happens when we don’t have all the components? • IoC Containers solve these issues – Have configuration – often external – Create objects – Ensure all dependencies are satisfied – Provide lifecycle support
  • 16. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 It Gets Better • We can use reflection to determine dependencies – no need for config files. • Most IoC containers support auto-wiring. • Make components known to container. • Container examines constructors and determines dependencies. • Auto-wiring provides other benefits. • Less typing, especially long assembly names. • Static type checking by IDE at edit time. • More intuitive for developer.
  • 17. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 IoC Containers and Features Container Setter DI Ctor DI External config Code config Auto- wiring Lifecycle support` Url System.ComponentModel a a Part of .Net framework PicoContainer.Net a a a a a http://picocontainer.org Windsor a a a ? a http://www.castleproject.org StructureMap a a a P a http://sourceforge.net/projects/structuremap Spring.Net a a a ? a a http://www.springframework.net/ ObjectBuilder a a a a ?? a http://msdn.microsoft.com ?? = More investigation ? = Setter based DI required for primitive dependencies P = Partial still requires configuration to point to assemblies to scan
  • 18. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 The Solution – Test Case [TestFixture] public class TradeMonitorTest { [Test] public void MonitorBlocksTradesWhenLimitExceeded() { DynamicMock mockRepository = new DynamicMock(typeof(ILimitRepository)); mockRepository.SetupResult('GetLimit', 1000000, new Type[] { typeof(string) }); mockRepository.SetupResult('GetExposure', 999999, new Type[] { typeof(string) }); TradeMonitor monitor = new TradeMonitor((ILimitRepository)mockRepository.MockInstance); Assert.IsFalse(monitor.TryTrade('MSFT', 1000), 'Monitor should block trade'); } } public class TradeMonitor { private ILimitRepository repository; public TradeMonitor(ILimitRepository repository) { this.repository = repository; } public bool TryTrade(string symbol, int amount) { int limit = repository.GetLimit(symbol); int exposure = repository.GetExposure(symbol); return ((amount + exposure) <= limit); } }
  • 19. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 The Solution – Using the Windsor Container • Code configuration IWindsorContainer container = new WindsorContainer(); container.AddComponent('limitRepository', typeof(ILimitRepository), typeof(LimitDao)); container.AddComponent('tradeMonitor', typeof(TradeMonitor)); TradeMonitor monitor = (TradeMonitor)container['tradeMonitor']; monitor.TryTrade('MSFT', 1000); • External configuration IWindsorContainer container = new WindsorContainer('config.xml'); TradeMonitor monitor = (TradeMonitor)container['tradeMonitor']; monitor.TryTrade('MSFT', 1000); <configuration> <components> <component id='limitRepository' service='AAABank.ILimitRepository, AAABank' type='AAABank.LimitDao, AAABank' /> <component id='tradeMonitor' type='AAABank.TradeMonitor, AAABank' /> </components> </configuration>
  • 20. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 The Solution – Complex Configuration • What if components take parameters? public class LimitDao { public LimitDao(string connectionString) {…} } public class TradeMonitor { public TradeMonitor(string[] monitoredSymbols) {…} } <configuration> <components> <component id='limitRepository' service='AAABank.ILimitRepository, AAABank' type='AAABank.LimitDao, AAABank'> <connectionString>Data Source=AServer;Initial Catalog=BankDB;User ID=sa</connectionString> </component> . . . <configuration> <components> <component id='tradeMonitor' type='AAABank.TradeMonitor, AAABank'> <monitoredSymbols> <array> <elem>MSFT</elem> <elem>TWUK</elem> </array> </monitoredSymbols> . . .
  • 21. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 Many other possibilities • Container creates objects – but what objects? • Can return proxy – no need for MarshalByRef inheritance. • Object instance caching. • Aspect Oriented Programming (concerns ,advice ,join point, pointcut). • Remoting by configuration. • Automatic Web Service creation. • . . .
  • 22. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 Summary • Container based DI facilitates: - – Testability – Extensibility – Reusability • Makes the difference between framework and library – Not just use but extend • Essential for complex Domain Driven Design – Easier to separate 'infrastructure' from business logic
  • 23. Amirkabir University of Technology (Tehran Polytechnic)- Fall 2011 Questions?