SlideShare una empresa de Scribd logo
1 de 67
http://slideshare.net/CalebJenkins
“The single greatest thing that you can do to make your
code more testable and healthy is to start taking a
Dependency Injection approach to writing software”
- Real World .NET, C# and Silverlight
Wrox Press 2012
Caleb Jenkins
Super Spy
(saves the world)
Dr. Evil
(bad guy)
public class DoubleOSuperSpy
{
public void StopDrEvilWithSpyWatch()
{
// Stop Dr. Evil
}
}
but what if we wanted to
rescue the queen
use our spy car
stop nuclear attack,
?
?
?
public class DoubleOSuperSpy
{
public void StopDrEvilWithSpyWatch()
{
// Stop Dr. Evil
}
public void StopDrEvilWithSpyCar()
{
}
public void SaveQueenWithSecretCrocodile()
{
}
// Etc...
}
public interface ISecretAgent
{
void RunMission(ISecretMission Mission);
}
public interface ISpyGadget
{
void UseGadget(string Target);
} public interface ISecretMission
{
}
public class SpyWatch : ISpyGadget
public class StopDrEvilMission : ISecretMission
public class DoubleOSuperSpy : ISecretAgent
public class DoubleOSuperSpy : ISecretAgent
{
private ISpyGadget spyWatch;
private IMission stopDrEvil;
public DoubleOSuperSpy()
{
spyWatch = new SpyWatch();
stopDrEvil = new StopDrEvilMission();
}
public void RunMission()
{
spyWatch.UseTo(stopDrEvil);
}
}
Separation of Concerns
+
Grouping of Features
=
Strategy Pattern
public class DoubleOSuperSpy : ISecretAgent
{
private ISpyGadget spyWatch;
private IMission stopDrEvil;
public DoubleOSuperSpy()
{
spyWatch = new SpyWatch();
stopDrEvil = new StopDrEvilMission();
}
public void RunMission()
{
spyWatch.UseTo(stopDrEvil);
}
}
Interfaces
=
Looser Coupling
public class Factory
{
public static ISecretAgent GetSecretAgent()
{
// Check config
return new DoubleOSuperSpy();
}
public static ISecretGadget GetSpyGadget()
{
// Check config
return new SpyWatch();
}
public static ISecretMission GetSecretMission()
{
// Check Config
return new StopDrEvilMission();
}
}
A Factory
Factory Pattern
public class DoubleOSuperSpy : ISecretAgent
{
private ISpyGadget gadget;
private ISecretMission mission;
public DoubleOSuperSpy()
{
gadget = Factory.GetSpyGadget();
mission = Factory.GetSecretMission();
}
public void UseGadget()
{
gadget.UserGadget(mission);
}
}
Abstract Factory Pattern
=
Abstraction of Creation
+
Polymorphism
public class DoubleOSuperSpy : ISecretAgent
{
private ISpyGadget gadget;
private ISecretMission mission;
public DoubleOSuperSpy()
{
gadget = Factory.GetSpyGadget();
mission = Factory.GetSecretMission();
}
public DoubleOSuperSpy (ISecretMission Mission,
ISpyGadget Gadget)
{
mission = Mission;
gadget = Gadget;
}
public ISpyGadget Gadget
{
set { gadget = Value; }
}
public void SetMission(ISecretMission Mission)
{
mission = Mission;
}
public void UseGadget()
{
gadget.UseGadget(mission);
}
public void UseGadget(ISecretMission Mission)
Factory Dependency
Dependency Injection
public class DoubleOSuperSpy : ISecretAgent
{
private ISpyGadget gadget;
private ISecretMission mission;
public DoubleOSuperSpy()
{
gadget = Factory.GetSpyGadget();
mission = Factory.GetSecretMission();
}
public DoubleOSuperSpy (ISecretMission Mission,
ISpyGadget Gadget)
{
mission = Mission;
gadget = Gadget;
}
public ISpyGadet Gadget
{
set { gadget = Value; }
}
public void SetMission(ISecretMission Mission)
{
mission = Mission;
}
public void UseWeapon(ISecretMission Mission)
{
gadget.UserGadget(Mission);
}
public void UseGadget()
public class DoubleOSuperSpy : ISecretAgent
{
private ISpyGadget gadget;
private ISecretMission mission;
public DoubleOSuperSpy()
{
gadget = Factory.GetSpyGadget();
mission = Factory.GetSecretMission();
}
public DoubleOSuperSpy (ISecretMission Mission,
ISpyGadget Gadget)
{
mission = Mission;
gadget = Gadget;
}
public ISpyGadget Gadget
{
set { gadget = Value; }
}
public void SetMission(ISecretMission Mission)
{
mission = Mission;
}
public void RunMission()
{
gadget.UseGadget(mission);
}
public void RunMission (ISecretMission Mission)
{
gadget.UseGadget(Mission);
}
public class DoubleOSuperSpy : ISecretAgent
{
private ISpyGadget gadget;
private ISecretMission mission;
private DoubleOSuperSpy()
{
}
public DoubleOSuperSpy (ISecretMission Mission,
ISpyGadget Gadget)
{
mission = Mission;
gadget = Gadget;
}
public void RunMission()
{
gadget.UseGadget(mission);
}
}
public class MyApplication
{
public void static Main()
{
ISecretAgent agent = Factory.GetSecretAgent();
ISpyGadget gadget = Factory.GetSpyGadget();
ISecretMission mission = Factory.GetSecretMission();
// Manual Dependency Injection
agent.SetMission(mission);
agent.SetGadget(gadget);
agent.RunMissionMission();
}
}
Manual
Dependency Injection
public class MyApplication
{
public void static Main()
{
ISpyGadget gadget = new SpyWatch();
ISecretMission mission = new StopDrEvilMission();
ISecretAgent agent = new DoubleOSuperSpy(gadget);
agent.RunMission(mission);
}
}
Manual
Dependency Injection
Factory
ISpyGadget
ISecretMission
ISecretAgent
MyApplication
Factory
ISpyGadget
ISecretMission
public class MyApplication
{
public void static Main()
{
ISecretAGent agent = Factory.GetSecretAgent();
ISpyGadget gadget = Factory.GetSpyGadget();
ISecretMission mission = Factory.GetSecretMission();
// Manual Dependency Injection
agent.SetMission(mission);
agent.SetSpyGadget(gadget);
agent.RunMission();
}
}
Manual
Dependency Injection
Manual
Dependency Injection
public class MyApplication
{
public void static Main()
{
ISecretAgent agent =
(ISecretAgent) Context.GetInstance(“ISecretAgent”);
}
}
Dependency Injection
Frameworks
Manual
Dependency Injection
public class MyApplication
{
public void static Main()
{
ISecretAgent agent =
(ISecretAgent) Context.GetInstance(“ISecretAgent”);
}
}
Dependency Injection
Frameworks
public class MyApplication
{
public void static Main()
{
ISecretAgent agent =
Context.GetInstance<ISecretAgent>();
}
}
Dependency Injection
(with Generics)
castleproject.org
springframework.net
ninject.org
unity.codeplex.com structuremap.github.io
simpleinjector.org
autofac.org
<factoryconfig type="Improving.ProviderFactory, ProviderFactory">
<factories>
<factory interface=“ISpyGadget" assembly=“Acme.MI6" class=“LaserSpyWatch“ />
<factory interface=“ISecretAgent" assembly=“Acme.MI6" class=“DoubleOSuperSpy”>
<params>
<param name=“Name" value=“Bond, James” type="System.String"/>
</params>
</factory>
<factory interface=“ISecretMission" assembly=“Acme.MI6" class=“StopDrEvilMission“
lifespan=“singleton”>
</factory>
</factories>
</factoryconfig>
Dependency Injection
Configuration Concepts
* Note: This is a conceptual configuration and not specific to any
IoC / di framework. Some IoC’s don’t use config, like Ninject that
relies on special [attributes] for mappings
public class DependencyConfigModule : StandardModule
{
public override void Load()
{
// Factory
Bind<IFactory>().To<factory>().Using<SingletonBehavior>();
// Models
Bind<ISecretAgent>().To<DoubleOSuperSpy>().Using<TransientBehavior>();
Bind<ISecretMission>().To<StopDrEvilMission>().Using<TransientBehavior>();
Bind<ISpyGadget>().To<LaserSpyWatch>().Using<TransientBehavior>();
}
}
Dependency Injection
Configuration Concepts
* Note: This is a conceptual configuration and not specific to any
IoC / di framework. Some IoC’s don’t use config, like Ninject that
relies on special [attributes] for mappings
public class DependencyConfigModule : StandardModule
{
public override void Load()
{
// Factory
Bind<IFactory>().To<factory>().Using<SingletonBehavior>();
// Models
Bind<ISecretAgent>().To<DoubleOSuperSpy>().Using<TransientBehavior>();
Bind<ISecretMission>().To<StopDrEvilMission>().Using<TransientBehavior>();
Bind<ISpyGadget>().To<LaserSpyWatch>().Using<TransientBehavior>();
}
}
<factoryconfig type="Improving.ProviderFactory, ProviderFactory">
<factories>
<factory interface=“ISpyGadget" assembly=“Acme.MI6" class=“LaserSpyWatch“ />
<factory interface=“ISecretAgent" assembly=“Acme.MI6" class=“DoubleOSuperSpy”>
<params>
<param name=“Name" value=“Bond, James” type="System.String"/>
</params>
</factory>
<factory interface=“ISecretMission" assembly=“Acme.MI6" class=“StopDrEvilMission“
lifespan=“singleton”>
</factory>
</factories>
</factoryconfig>
Dependency Injection
Configuration Concepts
Implementation Mapping
Simple Property Injection
Property Injection
Constructor Injection
Instantiation Model:
Singelton
Transient
Pool
* Note: This is a conceptual configuration and not specific to any
IoC / di framework. Some IoC’s don’t use config, like Ninject that
relies on special [attributes] for mappings
Interceptors / Listeners
Per Thread
Generics
LET’S LOOK AT
SOME CODE…
Interceptors and
Listeners
Interceptors and
Listeners
The mission has begun
Dr. Evil has been stopped!
It took :22 seconds!
Interceptors and Listeners
Stop Dr. Evil
Dynamic Proxy
Security must be
licensed to kill
(007)
Logging Bond is
about to begin
mission
Interceptors and Listeners (AOP)
Multi-Threading
Invoke UI Thread
Longest running “complete stack”
Windsor Container
Dynamic Proxy
Active Record (nHibernate)
ASP.NET Mono Rail
Visual Studio Tooling
Well Established Community
Integrates with ASP.NET MVC
ASP.NET | Sharepoint
Winforms | WPF | WCF | WF |
Console Apps
castleproject.org
springframework.net
“Spring Framework” is THE way to
do JAVA development
Spring .NET is the .NET equivalent
Nice bridge for Java Spring
developers moving to .NET
Interface 21
ninject.org
DI “gateway drug”
Light weight / super fast to configure
DI (Integrates with Castle for IoC / AOP)
.NET
Silverlight
Windows Mobile/Phone
No XML Config
(Fluent Config)
unity.codeplex.com
github.com/unitycontainer/unity
From Microsoft
Integration with other Application Blocks
Microsoft Support
Now Maintained by the community (OSS)
castleproject.org
springframework.net
ninject.org
unity.codeplex.com structuremap.github.io
simpleinjector.org
autofac.org
commonservicelocator.codeplex.com
IMPLEMENTATION
Castle Windsor Adapter
Spring .NET Adapter
Unity Adapter
StructureMap Adapter
Autofac Adapter
MEF Adapter now on .NET Framework 4.0
LinFu Adapter
Multi-target CSL binaries
Service Locator Adapter
Implementations
Common Service Locator
commonservicelocator.codeplex.com
Common Service Locator
commonservicelocator.codeplex.com
POOR MAN’S DIpublic class SuperSpyLib
{
private ISecretAgent agent;
private ISpyGadget gadget;
private ISecretMission mission;
public void SuperSpyLib (ISecretAgent Agent,
ISpyGadget Gadget, ISecretMission Mission)
{
agent = Agent;
gadget = Gadget;
mission = Mission;
}
}
POOR MAN’S DIpublic class SuperSpyLib
{
private ISecretAgent agent;
private ISpyGadget gadget;
private ISecretMission mission;
public void SuperSpyLib (ISecretAgent Agent,
ISpyGadget Gadget, ISecretMission Mission)
{
agent = Agent;
gadget = Gadget;
mission = Mission;
}
}
POOR MAN’S DIpublic class SuperSpyLib
{
private ISecretAgent agent;
private ISpyGadget gadget;
private ISecretMission mission;
public void SuperSpyLib (ISecretAgent Agent,
ISpyGadget Gadget, ISecretMission Mission)
{
agent = Agent;
gadget = Gadget;
mission = Mission;
}
}
public class SuperSpyLib
{
private ISecretAgent agent;
private ISpyGadget gadget;
private ISecretMission mission;
public void SuperSpyLib (ISecretAgent Agent,
ISpyGadget Gadget, ISecretMission Mission)
{
agent = Agent;
gadget = Gadget;
mission = Mission;
}
}
public void SuperSpyLib ()
: this (new SuperAgent(),
new SpyAgent(), new StopDrEvilMission())
{
// Default Constructor – Poor Man’s DI
}
POOR MAN’S DIpublic class SuperSpyLib
{
private ISecretAgent agent;
private ISpyGadget gadget;
private ISecretMission mission;
public void SuperSpyLib (ISecretAgent Agent,
ISpyGadget Gadget, ISecretMission Mission)
{
agent = Agent;
gadget = Gadget;
mission = Mission;
}
}
public class SuperSpyLib
{
private ISecretAgent agent;
private ISpyGadget gadget;
private ISecretMission mission;
public void SuperSpyLib (ISecretAgent Agent,
ISpyGadget Gadget, ISecretMission Mission)
{
agent = Agent;
gadget = Gadget;
mission = Mission;
}
}
public void SuperSpyLib ()
: this (new SuperAgent(),
new SpyAgent(), new StopDrEvilMission())
{
// Default Constructor – Poor Man’s DI
}
POOR MAN’S DIpublic class SuperSpyLib
{
private ISecretAgent agent;
private ISpyGadget gadget;
private ISecretMission mission;
public void SuperSpyLib (ISecretAgent Agent,
ISpyGadget Gadget, ISecretMission Mission)
{
agent = Agent;
gadget = Gadget;
mission = Mission;
}
}
public class SuperSpyLib
{
private ISecretAgent agent;
private ISpyGadget gadget;
private ISecretMission mission;
public void SuperSpyLib (ISecretAgent Agent,
ISpyGadget Gadget, ISecretMission Mission)
{
agent = Agent;
gadget = Gadget;
mission = Mission;
}
}
public void SuperSpyLib ()
: this (new SuperAgent(),
new SpyAgent(), new StopDrEvilMission())
{
// Default Constructor – Poor Man’s DI
}
developingUX.com
speakerpedia.com/speakers/caleb-jenkins
@calebjenkins
speakerpedia.com/prog
rammers
developingUX.com
speakerpedia.com/speakers/caleb-jenkins
@calebjenkins

Más contenido relacionado

La actualidad más candente

Google Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification GoogleGoogle Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification Google
Mathias Seguy
 
What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2
Santosh Singh Paliwal
 
Androidの本当にあった怖い話
Androidの本当にあった怖い話Androidの本当にあった怖い話
Androidの本当にあった怖い話
Yusuke Yamamoto
 

La actualidad más candente (20)

Google Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification GoogleGoogle Plus SignIn : l'Authentification Google
Google Plus SignIn : l'Authentification Google
 
Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!
 
Android camera2
Android camera2Android camera2
Android camera2
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2
 
What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2
 
Android Jetpack: ViewModel and Testing
Android Jetpack: ViewModel and TestingAndroid Jetpack: ViewModel and Testing
Android Jetpack: ViewModel and Testing
 
Modern Android Architecture
Modern Android ArchitectureModern Android Architecture
Modern Android Architecture
 
The Ring programming language version 1.5 book - Part 12 of 31
The Ring programming language version 1.5 book - Part 12 of 31The Ring programming language version 1.5 book - Part 12 of 31
The Ring programming language version 1.5 book - Part 12 of 31
 
Everything You (N)ever Wanted to Know about Testing View Controllers
Everything You (N)ever Wanted to Know about Testing View ControllersEverything You (N)ever Wanted to Know about Testing View Controllers
Everything You (N)ever Wanted to Know about Testing View Controllers
 
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"
 
Androidaop 170105090257
Androidaop 170105090257Androidaop 170105090257
Androidaop 170105090257
 
Androidの本当にあった怖い話
Androidの本当にあった怖い話Androidの本当にあった怖い話
Androidの本当にあった怖い話
 
Testing microservices: Tools and Frameworks
Testing microservices: Tools and FrameworksTesting microservices: Tools and Frameworks
Testing microservices: Tools and Frameworks
 
Effective Android Data Binding
Effective Android Data BindingEffective Android Data Binding
Effective Android Data Binding
 
RIBs - Fragments which work
RIBs - Fragments which workRIBs - Fragments which work
RIBs - Fragments which work
 
Quick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental SetupQuick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental Setup
 
README.MD for building the first purely digital mobile bank in Indonesia
README.MD for building the first purely digital mobile bank in Indonesia README.MD for building the first purely digital mobile bank in Indonesia
README.MD for building the first purely digital mobile bank in Indonesia
 
Testing view controllers with Quick and Nimble
Testing view controllers with Quick and NimbleTesting view controllers with Quick and Nimble
Testing view controllers with Quick and Nimble
 
Side effects-con-redux
Side effects-con-reduxSide effects-con-redux
Side effects-con-redux
 
Wicket 6
Wicket 6Wicket 6
Wicket 6
 

Similar a Code to DI For - Dependency Injection for Modern Applications

Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahoda
Droidcon Berlin
 
Parsley & Flex
Parsley & FlexParsley & Flex
Parsley & Flex
prideconan
 
Kick start your experience with android wear - Codemotion Rome 2015
Kick start your experience with android wear - Codemotion Rome 2015Kick start your experience with android wear - Codemotion Rome 2015
Kick start your experience with android wear - Codemotion Rome 2015
Codemotion
 
Real World Dependency Injection - IPC11 Spring Edition
Real World Dependency Injection - IPC11 Spring EditionReal World Dependency Injection - IPC11 Spring Edition
Real World Dependency Injection - IPC11 Spring Edition
Stephan Hochdörfer
 
Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13
Stephan Hochdörfer
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
Yekmer Simsek
 

Similar a Code to DI For - Dependency Injection for Modern Applications (20)

Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
 
Android Architecture Components
Android Architecture ComponentsAndroid Architecture Components
Android Architecture Components
 
Dependency injection in iOS
Dependency injection in iOSDependency injection in iOS
Dependency injection in iOS
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Improving android experience for both users and developers
Improving android experience for both users and developersImproving android experience for both users and developers
Improving android experience for both users and developers
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahoda
 
Dropwizard and Friends
Dropwizard and FriendsDropwizard and Friends
Dropwizard and Friends
 
Introduction to Backbone.js & Marionette.js
Introduction to Backbone.js & Marionette.jsIntroduction to Backbone.js & Marionette.js
Introduction to Backbone.js & Marionette.js
 
Designing for Windows Phone 8
Designing for Windows Phone 8Designing for Windows Phone 8
Designing for Windows Phone 8
 
Parsley & Flex
Parsley & FlexParsley & Flex
Parsley & Flex
 
Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SF
 
guice-servlet
guice-servletguice-servlet
guice-servlet
 
Kick start your experience with android wear - Codemotion Rome 2015
Kick start your experience with android wear - Codemotion Rome 2015Kick start your experience with android wear - Codemotion Rome 2015
Kick start your experience with android wear - Codemotion Rome 2015
 
TechDay: Kick Start Your Experience with Android Wear - Mario Viviani
TechDay: Kick Start Your Experience with Android Wear - Mario VivianiTechDay: Kick Start Your Experience with Android Wear - Mario Viviani
TechDay: Kick Start Your Experience with Android Wear - Mario Viviani
 
GDG Mediterranean Dev Fest Code lab #DevFestMed15 da android ad android wear ...
GDG Mediterranean Dev Fest Code lab #DevFestMed15 da android ad android wear ...GDG Mediterranean Dev Fest Code lab #DevFestMed15 da android ad android wear ...
GDG Mediterranean Dev Fest Code lab #DevFestMed15 da android ad android wear ...
 
Real World Dependency Injection - IPC11 Spring Edition
Real World Dependency Injection - IPC11 Spring EditionReal World Dependency Injection - IPC11 Spring Edition
Real World Dependency Injection - IPC11 Spring Edition
 
Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
YUI 3
YUI 3YUI 3
YUI 3
 

Más de Caleb Jenkins

10 Reasons Your Software Sucks - Election 2012 Edition
10 Reasons Your Software Sucks - Election 2012 Edition10 Reasons Your Software Sucks - Election 2012 Edition
10 Reasons Your Software Sucks - Election 2012 Edition
Caleb Jenkins
 

Más de Caleb Jenkins (20)

Coding Naked 2023
Coding Naked 2023Coding Naked 2023
Coding Naked 2023
 
Development Matters
Development MattersDevelopment Matters
Development Matters
 
Get your Hero Groove On - Heroes Reborn
Get your Hero Groove On - Heroes RebornGet your Hero Groove On - Heroes Reborn
Get your Hero Groove On - Heroes Reborn
 
Scaling Scrum with UX in the Enterprise
Scaling Scrum with UX in the EnterpriseScaling Scrum with UX in the Enterprise
Scaling Scrum with UX in the Enterprise
 
Modern Web - MVP Testable WebForms
Modern Web - MVP Testable WebFormsModern Web - MVP Testable WebForms
Modern Web - MVP Testable WebForms
 
10 Reasons Your Software Sucks 2014 - Tax Day Edition!
10 Reasons Your Software Sucks 2014 - Tax Day Edition!10 Reasons Your Software Sucks 2014 - Tax Day Edition!
10 Reasons Your Software Sucks 2014 - Tax Day Edition!
 
Modern ASP.NET Webskills
Modern ASP.NET WebskillsModern ASP.NET Webskills
Modern ASP.NET Webskills
 
Prototype Collaborate Innovate
Prototype Collaborate InnovatePrototype Collaborate Innovate
Prototype Collaborate Innovate
 
10 Reasons Your Software Sucks - Election 2012 Edition
10 Reasons Your Software Sucks - Election 2012 Edition10 Reasons Your Software Sucks - Election 2012 Edition
10 Reasons Your Software Sucks - Election 2012 Edition
 
Windows 8 & Phone 8 - an Architectural Battle Plan
Windows 8 & Phone 8 - an Architectural Battle PlanWindows 8 & Phone 8 - an Architectural Battle Plan
Windows 8 & Phone 8 - an Architectural Battle Plan
 
Scaling Scrum with UX
Scaling Scrum with UXScaling Scrum with UX
Scaling Scrum with UX
 
Coding Naked
Coding NakedCoding Naked
Coding Naked
 
Scaling Scrum with UX
Scaling Scrum with UXScaling Scrum with UX
Scaling Scrum with UX
 
Taming the Monster Legacy Code Beast
Taming the Monster Legacy Code BeastTaming the Monster Legacy Code Beast
Taming the Monster Legacy Code Beast
 
Silverlight for Mobile World Dominations
Silverlight for Mobile World DominationsSilverlight for Mobile World Dominations
Silverlight for Mobile World Dominations
 
.NET on the Cheap - Microsoft + OSS
.NET on the Cheap - Microsoft + OSS.NET on the Cheap - Microsoft + OSS
.NET on the Cheap - Microsoft + OSS
 
10 practices that every developer needs to start right now
10 practices that every developer needs to start right now10 practices that every developer needs to start right now
10 practices that every developer needs to start right now
 
Threat Modeling - Writing Secure Code
Threat Modeling - Writing Secure CodeThreat Modeling - Writing Secure Code
Threat Modeling - Writing Secure Code
 
Dependency Injection in Silverlight
Dependency Injection in SilverlightDependency Injection in Silverlight
Dependency Injection in Silverlight
 
Becoming A Presenter in the .NET World
Becoming A Presenter in the .NET WorldBecoming A Presenter in the .NET World
Becoming A Presenter in the .NET World
 

Último

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Último (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 

Code to DI For - Dependency Injection for Modern Applications

  • 1.
  • 2.
  • 3.
  • 5.
  • 6. “The single greatest thing that you can do to make your code more testable and healthy is to start taking a Dependency Injection approach to writing software” - Real World .NET, C# and Silverlight Wrox Press 2012 Caleb Jenkins
  • 7.
  • 8.
  • 9.
  • 10. Super Spy (saves the world) Dr. Evil (bad guy)
  • 11. public class DoubleOSuperSpy { public void StopDrEvilWithSpyWatch() { // Stop Dr. Evil } }
  • 12. but what if we wanted to rescue the queen use our spy car stop nuclear attack,
  • 13. ?
  • 14. ?
  • 15. ?
  • 16. public class DoubleOSuperSpy { public void StopDrEvilWithSpyWatch() { // Stop Dr. Evil } public void StopDrEvilWithSpyCar() { } public void SaveQueenWithSecretCrocodile() { } // Etc... }
  • 17.
  • 18. public interface ISecretAgent { void RunMission(ISecretMission Mission); } public interface ISpyGadget { void UseGadget(string Target); } public interface ISecretMission { } public class SpyWatch : ISpyGadget public class StopDrEvilMission : ISecretMission public class DoubleOSuperSpy : ISecretAgent
  • 19. public class DoubleOSuperSpy : ISecretAgent { private ISpyGadget spyWatch; private IMission stopDrEvil; public DoubleOSuperSpy() { spyWatch = new SpyWatch(); stopDrEvil = new StopDrEvilMission(); } public void RunMission() { spyWatch.UseTo(stopDrEvil); } } Separation of Concerns + Grouping of Features = Strategy Pattern
  • 20. public class DoubleOSuperSpy : ISecretAgent { private ISpyGadget spyWatch; private IMission stopDrEvil; public DoubleOSuperSpy() { spyWatch = new SpyWatch(); stopDrEvil = new StopDrEvilMission(); } public void RunMission() { spyWatch.UseTo(stopDrEvil); } } Interfaces = Looser Coupling
  • 21. public class Factory { public static ISecretAgent GetSecretAgent() { // Check config return new DoubleOSuperSpy(); } public static ISecretGadget GetSpyGadget() { // Check config return new SpyWatch(); } public static ISecretMission GetSecretMission() { // Check Config return new StopDrEvilMission(); } } A Factory
  • 23. public class DoubleOSuperSpy : ISecretAgent { private ISpyGadget gadget; private ISecretMission mission; public DoubleOSuperSpy() { gadget = Factory.GetSpyGadget(); mission = Factory.GetSecretMission(); } public void UseGadget() { gadget.UserGadget(mission); } } Abstract Factory Pattern = Abstraction of Creation + Polymorphism
  • 24. public class DoubleOSuperSpy : ISecretAgent { private ISpyGadget gadget; private ISecretMission mission; public DoubleOSuperSpy() { gadget = Factory.GetSpyGadget(); mission = Factory.GetSecretMission(); } public DoubleOSuperSpy (ISecretMission Mission, ISpyGadget Gadget) { mission = Mission; gadget = Gadget; } public ISpyGadget Gadget { set { gadget = Value; } } public void SetMission(ISecretMission Mission) { mission = Mission; } public void UseGadget() { gadget.UseGadget(mission); } public void UseGadget(ISecretMission Mission) Factory Dependency Dependency Injection
  • 25. public class DoubleOSuperSpy : ISecretAgent { private ISpyGadget gadget; private ISecretMission mission; public DoubleOSuperSpy() { gadget = Factory.GetSpyGadget(); mission = Factory.GetSecretMission(); } public DoubleOSuperSpy (ISecretMission Mission, ISpyGadget Gadget) { mission = Mission; gadget = Gadget; } public ISpyGadet Gadget { set { gadget = Value; } } public void SetMission(ISecretMission Mission) { mission = Mission; } public void UseWeapon(ISecretMission Mission) { gadget.UserGadget(Mission); } public void UseGadget()
  • 26. public class DoubleOSuperSpy : ISecretAgent { private ISpyGadget gadget; private ISecretMission mission; public DoubleOSuperSpy() { gadget = Factory.GetSpyGadget(); mission = Factory.GetSecretMission(); } public DoubleOSuperSpy (ISecretMission Mission, ISpyGadget Gadget) { mission = Mission; gadget = Gadget; } public ISpyGadget Gadget { set { gadget = Value; } } public void SetMission(ISecretMission Mission) { mission = Mission; } public void RunMission() { gadget.UseGadget(mission); } public void RunMission (ISecretMission Mission) { gadget.UseGadget(Mission); }
  • 27. public class DoubleOSuperSpy : ISecretAgent { private ISpyGadget gadget; private ISecretMission mission; private DoubleOSuperSpy() { } public DoubleOSuperSpy (ISecretMission Mission, ISpyGadget Gadget) { mission = Mission; gadget = Gadget; } public void RunMission() { gadget.UseGadget(mission); } }
  • 28. public class MyApplication { public void static Main() { ISecretAgent agent = Factory.GetSecretAgent(); ISpyGadget gadget = Factory.GetSpyGadget(); ISecretMission mission = Factory.GetSecretMission(); // Manual Dependency Injection agent.SetMission(mission); agent.SetGadget(gadget); agent.RunMissionMission(); } } Manual Dependency Injection
  • 29. public class MyApplication { public void static Main() { ISpyGadget gadget = new SpyWatch(); ISecretMission mission = new StopDrEvilMission(); ISecretAgent agent = new DoubleOSuperSpy(gadget); agent.RunMission(mission); } } Manual Dependency Injection
  • 30.
  • 31.
  • 33. public class MyApplication { public void static Main() { ISecretAGent agent = Factory.GetSecretAgent(); ISpyGadget gadget = Factory.GetSpyGadget(); ISecretMission mission = Factory.GetSecretMission(); // Manual Dependency Injection agent.SetMission(mission); agent.SetSpyGadget(gadget); agent.RunMission(); } } Manual Dependency Injection
  • 34. Manual Dependency Injection public class MyApplication { public void static Main() { ISecretAgent agent = (ISecretAgent) Context.GetInstance(“ISecretAgent”); } } Dependency Injection Frameworks
  • 35. Manual Dependency Injection public class MyApplication { public void static Main() { ISecretAgent agent = (ISecretAgent) Context.GetInstance(“ISecretAgent”); } } Dependency Injection Frameworks public class MyApplication { public void static Main() { ISecretAgent agent = Context.GetInstance<ISecretAgent>(); } } Dependency Injection (with Generics)
  • 37. <factoryconfig type="Improving.ProviderFactory, ProviderFactory"> <factories> <factory interface=“ISpyGadget" assembly=“Acme.MI6" class=“LaserSpyWatch“ /> <factory interface=“ISecretAgent" assembly=“Acme.MI6" class=“DoubleOSuperSpy”> <params> <param name=“Name" value=“Bond, James” type="System.String"/> </params> </factory> <factory interface=“ISecretMission" assembly=“Acme.MI6" class=“StopDrEvilMission“ lifespan=“singleton”> </factory> </factories> </factoryconfig> Dependency Injection Configuration Concepts * Note: This is a conceptual configuration and not specific to any IoC / di framework. Some IoC’s don’t use config, like Ninject that relies on special [attributes] for mappings
  • 38. public class DependencyConfigModule : StandardModule { public override void Load() { // Factory Bind<IFactory>().To<factory>().Using<SingletonBehavior>(); // Models Bind<ISecretAgent>().To<DoubleOSuperSpy>().Using<TransientBehavior>(); Bind<ISecretMission>().To<StopDrEvilMission>().Using<TransientBehavior>(); Bind<ISpyGadget>().To<LaserSpyWatch>().Using<TransientBehavior>(); } } Dependency Injection Configuration Concepts * Note: This is a conceptual configuration and not specific to any IoC / di framework. Some IoC’s don’t use config, like Ninject that relies on special [attributes] for mappings
  • 39. public class DependencyConfigModule : StandardModule { public override void Load() { // Factory Bind<IFactory>().To<factory>().Using<SingletonBehavior>(); // Models Bind<ISecretAgent>().To<DoubleOSuperSpy>().Using<TransientBehavior>(); Bind<ISecretMission>().To<StopDrEvilMission>().Using<TransientBehavior>(); Bind<ISpyGadget>().To<LaserSpyWatch>().Using<TransientBehavior>(); } } <factoryconfig type="Improving.ProviderFactory, ProviderFactory"> <factories> <factory interface=“ISpyGadget" assembly=“Acme.MI6" class=“LaserSpyWatch“ /> <factory interface=“ISecretAgent" assembly=“Acme.MI6" class=“DoubleOSuperSpy”> <params> <param name=“Name" value=“Bond, James” type="System.String"/> </params> </factory> <factory interface=“ISecretMission" assembly=“Acme.MI6" class=“StopDrEvilMission“ lifespan=“singleton”> </factory> </factories> </factoryconfig> Dependency Injection Configuration Concepts Implementation Mapping Simple Property Injection Property Injection Constructor Injection Instantiation Model: Singelton Transient Pool * Note: This is a conceptual configuration and not specific to any IoC / di framework. Some IoC’s don’t use config, like Ninject that relies on special [attributes] for mappings Interceptors / Listeners Per Thread Generics
  • 43. The mission has begun Dr. Evil has been stopped! It took :22 seconds! Interceptors and Listeners
  • 44. Stop Dr. Evil Dynamic Proxy Security must be licensed to kill (007) Logging Bond is about to begin mission Interceptors and Listeners (AOP) Multi-Threading Invoke UI Thread
  • 45. Longest running “complete stack” Windsor Container Dynamic Proxy Active Record (nHibernate) ASP.NET Mono Rail Visual Studio Tooling Well Established Community Integrates with ASP.NET MVC ASP.NET | Sharepoint Winforms | WPF | WCF | WF | Console Apps castleproject.org
  • 46. springframework.net “Spring Framework” is THE way to do JAVA development Spring .NET is the .NET equivalent Nice bridge for Java Spring developers moving to .NET Interface 21
  • 47. ninject.org DI “gateway drug” Light weight / super fast to configure DI (Integrates with Castle for IoC / AOP) .NET Silverlight Windows Mobile/Phone No XML Config (Fluent Config)
  • 48. unity.codeplex.com github.com/unitycontainer/unity From Microsoft Integration with other Application Blocks Microsoft Support Now Maintained by the community (OSS)
  • 50. commonservicelocator.codeplex.com IMPLEMENTATION Castle Windsor Adapter Spring .NET Adapter Unity Adapter StructureMap Adapter Autofac Adapter MEF Adapter now on .NET Framework 4.0 LinFu Adapter Multi-target CSL binaries Service Locator Adapter Implementations
  • 53. POOR MAN’S DIpublic class SuperSpyLib { private ISecretAgent agent; private ISpyGadget gadget; private ISecretMission mission; public void SuperSpyLib (ISecretAgent Agent, ISpyGadget Gadget, ISecretMission Mission) { agent = Agent; gadget = Gadget; mission = Mission; } }
  • 54. POOR MAN’S DIpublic class SuperSpyLib { private ISecretAgent agent; private ISpyGadget gadget; private ISecretMission mission; public void SuperSpyLib (ISecretAgent Agent, ISpyGadget Gadget, ISecretMission Mission) { agent = Agent; gadget = Gadget; mission = Mission; } }
  • 55. POOR MAN’S DIpublic class SuperSpyLib { private ISecretAgent agent; private ISpyGadget gadget; private ISecretMission mission; public void SuperSpyLib (ISecretAgent Agent, ISpyGadget Gadget, ISecretMission Mission) { agent = Agent; gadget = Gadget; mission = Mission; } } public class SuperSpyLib { private ISecretAgent agent; private ISpyGadget gadget; private ISecretMission mission; public void SuperSpyLib (ISecretAgent Agent, ISpyGadget Gadget, ISecretMission Mission) { agent = Agent; gadget = Gadget; mission = Mission; } } public void SuperSpyLib () : this (new SuperAgent(), new SpyAgent(), new StopDrEvilMission()) { // Default Constructor – Poor Man’s DI }
  • 56. POOR MAN’S DIpublic class SuperSpyLib { private ISecretAgent agent; private ISpyGadget gadget; private ISecretMission mission; public void SuperSpyLib (ISecretAgent Agent, ISpyGadget Gadget, ISecretMission Mission) { agent = Agent; gadget = Gadget; mission = Mission; } } public class SuperSpyLib { private ISecretAgent agent; private ISpyGadget gadget; private ISecretMission mission; public void SuperSpyLib (ISecretAgent Agent, ISpyGadget Gadget, ISecretMission Mission) { agent = Agent; gadget = Gadget; mission = Mission; } } public void SuperSpyLib () : this (new SuperAgent(), new SpyAgent(), new StopDrEvilMission()) { // Default Constructor – Poor Man’s DI }
  • 57. POOR MAN’S DIpublic class SuperSpyLib { private ISecretAgent agent; private ISpyGadget gadget; private ISecretMission mission; public void SuperSpyLib (ISecretAgent Agent, ISpyGadget Gadget, ISecretMission Mission) { agent = Agent; gadget = Gadget; mission = Mission; } } public class SuperSpyLib { private ISecretAgent agent; private ISpyGadget gadget; private ISecretMission mission; public void SuperSpyLib (ISecretAgent Agent, ISpyGadget Gadget, ISecretMission Mission) { agent = Agent; gadget = Gadget; mission = Mission; } } public void SuperSpyLib () : this (new SuperAgent(), new SpyAgent(), new StopDrEvilMission()) { // Default Constructor – Poor Man’s DI }
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 66.

Notas del editor

  1. 59