SlideShare une entreprise Scribd logo
1  sur  23
Dependency Injection And using an Inversion of Control (IoC) container
What is Dependency Injection Giving an object instance it’s variables
Dependency Non-Injection public class Whatever {   private DbStuff _db;   This is a variable   public Whatever()  {    _db = new DbStuff();   And Whatever  }                          depends on it so it creates it   public void DoIt()  {    _db.GetData();  } }
And this is bad for all kinds of reasons…
Single Responsibility Principle A class should have one, and only one, reason to change. We switch from SQL Server to Oracle and our Whatever class needs to change
Dependency Injection public class Whatever {   private DbStuff_db;   public Whatever(DbStuff database)  {    _db = database;   The ‘new’ keyword  }                     is outta there   public void DoIt()  {    _db.GetData();  } }
Win Our Whateverclass still depends on DbDatabut it is not responsible for it By adhering to SRP through dependency injection we increasecohesion
But wait! We still have a problem
Dependency Inversion Principle Depend on abstractions, not on concretions. We can improve the situation by depending on an interface or abstract class
Dependency Injection v 2.0 public class Whatever {   private IDbStuff _db;    Better   public Whatever(IDbStuff database)  {    _db = database;   life is good  }   public void DoIt()  {    _db.GetData();  } }
To summarize, DI is about passing instance variables
Benefits High cohesion because classes are focused on doing one thing really well Testability IDbStuff data = new FakeDbWithBadData(); var test = new Whatever(data); Assert.Throws(Exception,test.DoIt()); The class under test did not have to change. Magic!
private readonlySystemConfiguration _configuration; private readonlyIWorkorderEntityBuilder _entityBuilder; public NewEntityWorkorderManager(IWorkorderRepositoryworkorderRepository, IMessageRepositorymessageRepository, IWorkorderEntityBuilderentityBuilder, SystemConfiguration configuration, ICityworksRepositorycityworksRepository) : base(workorderRepository, messageRepository, cityworksRepository, configuration)         {             _entityBuilder = entityBuilder;             _configuration = configuration;         }
Inversion of Control Containers (IoC is a terrible term but we’re stuck with it. But maybe we’ll use container instead. At least it’s shorter.)
Manage Dependencies DI makes for cohesive, loosely couple software But also more moving parts IoC containers exist to make dependency injection easier and more predictable
ContainersA Short List Spring Spring.NET Pico Castle Windsor StructureMap Ninject Autofac Unity Glassfish and any EJB 3.0 app server
Workflow
ForRequestedType<ISpatialQuery>()                .TheDefaultIsConcreteType<SpatialQueryGenericClient>();
ForRequestedType<ISettingRepository>()                .TheDefault.Is.OfConcreteType<ApplicationSettingRepository>()                .CtorDependency<IUnitOfWork>("unitOfWork")                .Is(u => u.TheInstanceNamed(Resources.WCSDatasource));
var settings = ObjectFactory.GetInstance<ISettingRepository>();
Autowiring Is A Big Win
Things depend on things depend on things… varprocessor = ObjectFactory.GetInstance<IMessageProcessor>();
Features Many other features but that’s the core Manage lifetime of objects Singleton, per-thread, per-session XML configuration

Contenu connexe

Tendances

DCI
DCIDCI
DCIlpld
 
Drools Introduction
Drools IntroductionDrools Introduction
Drools Introductionlakshmi1693
 
Object Oriented Terms
Object Oriented TermsObject Oriented Terms
Object Oriented Termsguest3c69aefa
 
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...Marco Tusa
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Vagif Abilov
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpaStaples
 
Python Deserialization Attacks
Python Deserialization AttacksPython Deserialization Attacks
Python Deserialization AttacksNSConclave
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Functional Dependency Injection in C#
Functional Dependency Injection in C#Functional Dependency Injection in C#
Functional Dependency Injection in C#Thomas Jaskula
 
Testdrevet javautvikling på objektorienterte skinner
Testdrevet javautvikling på objektorienterte skinnerTestdrevet javautvikling på objektorienterte skinner
Testdrevet javautvikling på objektorienterte skinnerTruls Jørgensen
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0PhilWinstanley
 

Tendances (20)

DCI
DCIDCI
DCI
 
Jpa 2.1 Application Development
Jpa 2.1 Application DevelopmentJpa 2.1 Application Development
Jpa 2.1 Application Development
 
Drools Introduction
Drools IntroductionDrools Introduction
Drools Introduction
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
Object Oriented Terms
Object Oriented TermsObject Oriented Terms
Object Oriented Terms
 
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
 
Ecom lec4 fall16_jpa
Ecom lec4 fall16_jpaEcom lec4 fall16_jpa
Ecom lec4 fall16_jpa
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#
 
Design Patterns: Back to Basics
Design Patterns: Back to BasicsDesign Patterns: Back to Basics
Design Patterns: Back to Basics
 
TY.BSc.IT Java QB U2
TY.BSc.IT Java QB U2TY.BSc.IT Java QB U2
TY.BSc.IT Java QB U2
 
Deployment
DeploymentDeployment
Deployment
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
 
Python Deserialization Attacks
Python Deserialization AttacksPython Deserialization Attacks
Python Deserialization Attacks
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
Functional Dependency Injection in C#
Functional Dependency Injection in C#Functional Dependency Injection in C#
Functional Dependency Injection in C#
 
Testdrevet javautvikling på objektorienterte skinner
Testdrevet javautvikling på objektorienterte skinnerTestdrevet javautvikling på objektorienterte skinner
Testdrevet javautvikling på objektorienterte skinner
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 

Similaire à Dev Cast Dependency Injection

Dao pattern
Dao patternDao pattern
Dao patternciriako
 
Dependency Injection або Don’t call me, I’ll call you
Dependency Injection або Don’t call me, I’ll call youDependency Injection або Don’t call me, I’ll call you
Dependency Injection або Don’t call me, I’ll call youDmytro Mindra
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Greg Szczotka
 
Dependency injection with unity 2.0 Dmytro Mindra Lohika
Dependency injection with unity 2.0 Dmytro Mindra LohikaDependency injection with unity 2.0 Dmytro Mindra Lohika
Dependency injection with unity 2.0 Dmytro Mindra LohikaAlex Tumanoff
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC PrinciplesPavlo Hodysh
 
Sql server difference faqs- 3
Sql server difference faqs- 3Sql server difference faqs- 3
Sql server difference faqs- 3Umar Ali
 
Code to DI For - Dependency Injection for Modern Applications
Code to DI For - Dependency Injection for Modern ApplicationsCode to DI For - Dependency Injection for Modern Applications
Code to DI For - Dependency Injection for Modern ApplicationsCaleb Jenkins
 
Make it test-driven with CDI!
Make it test-driven with CDI!Make it test-driven with CDI!
Make it test-driven with CDI!rafaelliu
 
What's new and noteworthy in Java EE 8?
What's new and noteworthy in Java EE 8?What's new and noteworthy in Java EE 8?
What's new and noteworthy in Java EE 8?gedoplan
 
NodeJS Spring style Inversifyjs
NodeJS Spring style InversifyjsNodeJS Spring style Inversifyjs
NodeJS Spring style InversifyjsMathieu Breton
 
Integration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBIntegration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBMichal Bigos
 
JSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan ZarnikovJSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan ZarnikovChristoph Pickl
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice PresentationDmitry Buzdin
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofacmeghantaylor
 

Similaire à Dev Cast Dependency Injection (20)

Dao pattern
Dao patternDao pattern
Dao pattern
 
Dependency Injection або Don’t call me, I’ll call you
Dependency Injection або Don’t call me, I’ll call youDependency Injection або Don’t call me, I’ll call you
Dependency Injection або Don’t call me, I’ll call you
 
IOC in unity
IOC in unityIOC in unity
IOC in unity
 
IOC in Unity
IOC in Unity  IOC in Unity
IOC in Unity
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014
 
Dependency injection with unity 2.0 Dmytro Mindra Lohika
Dependency injection with unity 2.0 Dmytro Mindra LohikaDependency injection with unity 2.0 Dmytro Mindra Lohika
Dependency injection with unity 2.0 Dmytro Mindra Lohika
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC Principles
 
Sql server difference faqs- 3
Sql server difference faqs- 3Sql server difference faqs- 3
Sql server difference faqs- 3
 
Code to DI For - Dependency Injection for Modern Applications
Code to DI For - Dependency Injection for Modern ApplicationsCode to DI For - Dependency Injection for Modern Applications
Code to DI For - Dependency Injection for Modern Applications
 
java arlow jdbc tutorial(java programming tutorials)
java arlow jdbc tutorial(java programming tutorials)java arlow jdbc tutorial(java programming tutorials)
java arlow jdbc tutorial(java programming tutorials)
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Make it test-driven with CDI!
Make it test-driven with CDI!Make it test-driven with CDI!
Make it test-driven with CDI!
 
What's new and noteworthy in Java EE 8?
What's new and noteworthy in Java EE 8?What's new and noteworthy in Java EE 8?
What's new and noteworthy in Java EE 8?
 
NodeJS Spring style Inversifyjs
NodeJS Spring style InversifyjsNodeJS Spring style Inversifyjs
NodeJS Spring style Inversifyjs
 
Integration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBIntegration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDB
 
JSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan ZarnikovJSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan Zarnikov
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice Presentation
 
iOS Talks 6: Unit Testing
iOS Talks 6: Unit TestingiOS Talks 6: Unit Testing
iOS Talks 6: Unit Testing
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
 

Dernier

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 

Dernier (20)

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 

Dev Cast Dependency Injection

  • 1. Dependency Injection And using an Inversion of Control (IoC) container
  • 2. What is Dependency Injection Giving an object instance it’s variables
  • 3. Dependency Non-Injection public class Whatever { private DbStuff _db;  This is a variable public Whatever() { _db = new DbStuff();  And Whatever } depends on it so it creates it public void DoIt() { _db.GetData(); } }
  • 4. And this is bad for all kinds of reasons…
  • 5. Single Responsibility Principle A class should have one, and only one, reason to change. We switch from SQL Server to Oracle and our Whatever class needs to change
  • 6. Dependency Injection public class Whatever { private DbStuff_db; public Whatever(DbStuff database) { _db = database;  The ‘new’ keyword } is outta there public void DoIt() { _db.GetData(); } }
  • 7. Win Our Whateverclass still depends on DbDatabut it is not responsible for it By adhering to SRP through dependency injection we increasecohesion
  • 8. But wait! We still have a problem
  • 9. Dependency Inversion Principle Depend on abstractions, not on concretions. We can improve the situation by depending on an interface or abstract class
  • 10. Dependency Injection v 2.0 public class Whatever { private IDbStuff _db;  Better public Whatever(IDbStuff database) { _db = database;  life is good } public void DoIt() { _db.GetData(); } }
  • 11. To summarize, DI is about passing instance variables
  • 12. Benefits High cohesion because classes are focused on doing one thing really well Testability IDbStuff data = new FakeDbWithBadData(); var test = new Whatever(data); Assert.Throws(Exception,test.DoIt()); The class under test did not have to change. Magic!
  • 13. private readonlySystemConfiguration _configuration; private readonlyIWorkorderEntityBuilder _entityBuilder; public NewEntityWorkorderManager(IWorkorderRepositoryworkorderRepository, IMessageRepositorymessageRepository, IWorkorderEntityBuilderentityBuilder, SystemConfiguration configuration, ICityworksRepositorycityworksRepository) : base(workorderRepository, messageRepository, cityworksRepository, configuration) { _entityBuilder = entityBuilder; _configuration = configuration; }
  • 14. Inversion of Control Containers (IoC is a terrible term but we’re stuck with it. But maybe we’ll use container instead. At least it’s shorter.)
  • 15. Manage Dependencies DI makes for cohesive, loosely couple software But also more moving parts IoC containers exist to make dependency injection easier and more predictable
  • 16. ContainersA Short List Spring Spring.NET Pico Castle Windsor StructureMap Ninject Autofac Unity Glassfish and any EJB 3.0 app server
  • 18. ForRequestedType<ISpatialQuery>() .TheDefaultIsConcreteType<SpatialQueryGenericClient>();
  • 19. ForRequestedType<ISettingRepository>() .TheDefault.Is.OfConcreteType<ApplicationSettingRepository>() .CtorDependency<IUnitOfWork>("unitOfWork") .Is(u => u.TheInstanceNamed(Resources.WCSDatasource));
  • 20. var settings = ObjectFactory.GetInstance<ISettingRepository>();
  • 21. Autowiring Is A Big Win
  • 22. Things depend on things depend on things… varprocessor = ObjectFactory.GetInstance<IMessageProcessor>();
  • 23. Features Many other features but that’s the core Manage lifetime of objects Singleton, per-thread, per-session XML configuration