SlideShare a Scribd company logo
Code to DI For - Dependency Injection for Modern Applications
Code to DI For - Dependency Injection for Modern Applications
Code to DI For - Dependency Injection for Modern Applications
http://slideshare.net/CalebJenkins
Code to DI For - Dependency Injection for Modern Applications
“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
Code to DI For - Dependency Injection for Modern Applications
Code to DI For - Dependency Injection for Modern Applications
Code to DI For - Dependency Injection for Modern Applications
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...
}
Code to DI For - Dependency Injection for Modern Applications
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
Code to DI For - Dependency Injection for Modern Applications
Code to DI For - Dependency Injection for Modern Applications
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
}
Code to DI For - Dependency Injection for Modern Applications
Code to DI For - Dependency Injection for Modern Applications
Code to DI For - Dependency Injection for Modern Applications
Code to DI For - Dependency Injection for Modern Applications
Code to DI For - Dependency Injection for Modern Applications
Code to DI For - Dependency Injection for Modern Applications
developingUX.com
speakerpedia.com/speakers/caleb-jenkins
@calebjenkins
speakerpedia.com/prog
rammers
Code to DI For - Dependency Injection for Modern Applications
developingUX.com
speakerpedia.com/speakers/caleb-jenkins
@calebjenkins

More Related Content

PDF
More android code puzzles
PDF
Android code puzzlers + tips & tricks
PDF
Capture image on eye blink
PDF
Automated%20testing%20with%20Espresso2.x
PDF
Android Design Patterns
PDF
Android Unit Testing With Robolectric
PDF
The Ring programming language version 1.7 book - Part 75 of 196
PDF
The Ring programming language version 1.8 book - Part 77 of 202
More android code puzzles
Android code puzzlers + tips & tricks
Capture image on eye blink
Automated%20testing%20with%20Espresso2.x
Android Design Patterns
Android Unit Testing With Robolectric
The Ring programming language version 1.7 book - Part 75 of 196
The Ring programming language version 1.8 book - Part 77 of 202

What's hot (20)

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

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

PPT
Manage software dependencies with ioc and aop
PDF
Designing For Change
PPT
PPTX
Dependency injection with unity 2.0 Dmytro Mindra Lohika
PDF
Анатолій Ландишев - “Незв’язний код у Unity” GameCC 2017
PPTX
Design for testability as a way to good coding (SOLID and IoC)
PPTX
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
PDF
Developing Useful APIs
PPT
Dependency injection
PPTX
Design pattern part 2 - structural pattern
PDF
Dot Net Design Patterns Interview Questions PDF By ScholarHat
PPTX
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
PPTX
Clean Code Part II - Dependency Injection at SoCal Code Camp
PPT
Ef Poco And Unit Testing
PPTX
Dependency Injection або Don’t call me, I’ll call you
PPTX
Binding Objective-C Libraries, Miguel de Icaza
PPTX
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
PDF
Dawn - Actionscript Library
Manage software dependencies with ioc and aop
Designing For Change
Dependency injection with unity 2.0 Dmytro Mindra Lohika
Анатолій Ландишев - “Незв’язний код у Unity” GameCC 2017
Design for testability as a way to good coding (SOLID and IoC)
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Developing Useful APIs
Dependency injection
Design pattern part 2 - structural pattern
Dot Net Design Patterns Interview Questions PDF By ScholarHat
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Clean Code Part II - Dependency Injection at SoCal Code Camp
Ef Poco And Unit Testing
Dependency Injection або Don’t call me, I’ll call you
Binding Objective-C Libraries, Miguel de Icaza
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Dawn - Actionscript Library
Ad

More from Caleb Jenkins (20)

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

Recently uploaded (20)

PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Introduction to Artificial Intelligence
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
AI in Product Development-omnex systems
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
L1 - Introduction to python Backend.pptx
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
System and Network Administration Chapter 2
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
history of c programming in notes for students .pptx
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
ai tools demonstartion for schools and inter college
Design an Analysis of Algorithms I-SECS-1021-03
How to Choose the Right IT Partner for Your Business in Malaysia
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Introduction to Artificial Intelligence
VVF-Customer-Presentation2025-Ver1.9.pptx
AI in Product Development-omnex systems
Navsoft: AI-Powered Business Solutions & Custom Software Development
L1 - Introduction to python Backend.pptx
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
How Creative Agencies Leverage Project Management Software.pdf
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
System and Network Administration Chapter 2
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Which alternative to Crystal Reports is best for small or large businesses.pdf
Upgrade and Innovation Strategies for SAP ERP Customers
history of c programming in notes for students .pptx
Design an Analysis of Algorithms II-SECS-1021-03
ai tools demonstartion for schools and inter college

Code to DI For - Dependency Injection for Modern Applications

  • 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
  • 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... }
  • 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
  • 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 }

Editor's Notes