SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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
 

Último

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 

Último (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 

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