SlideShare a Scribd company logo
1 of 18
Dependency Injection with .NET
-OR-
So you’ve decided to finally inject
your dependencies
-OR-
Let’s test production scenarios so it
doesn’t break
Overview
• What is DI?
• Why use DI?
• Where to use DI?
• How to do DI?
• C#, Legacy Code, and DI
– Interfaces, and Singletons, and Mocks, oh my!
What is Dependency Injection
• A software design pattern that implements inversion of
control for resolving dependencies. A dependency is an
object that can be used (a service). An injection is the passing
of a dependency to a dependent object (a client) that would
use it.
– Wikipedia
AppIoC
Dependency
Concrete
Implementation
Concrete
Implementation
Concrete
Implementation
Dependency Inject – An Example
• Legacy code w/o DI
public class ReviewManager{
public ElasticSearchBackedReviewRepository ReviewsRepo
{get; set;}
public void GetReviewsByMovie( int movieId){
return
ElasticSearchBackedReviewRepository.GetReviews(movieId);
}
}
• Legacy code w/o DI
public class ReviewManager{
public IReviewRepository ReviewsRepo {get; set;}
Public ReviewManager( IReviewRepository repo ){
ReviewsRepo = repo;
}
public void GetReviewsByMovie( int movieId){
return ReviewsRepo.GetReviews(moviedId);
}
}
AppIoC
Dependency
Concrete
Implementation
Concrete
Implementation
Concrete
Implementation
Why Interfaces?
• Develop against a contract
– Business logic isn’t changed as new
implementations are introduced
• Moq (for unit tests) requires interfaces or
virtual methods.
• All wiring for dependencies can be performed
in a centralized location
Why Mocking?
• Allows testing any use case without the need
for test data
– Mock a response that returns the use case you are
testing (as opposed to test data in the DB)
– Null return values
– Timeout (web service clients)
– 0 reviews, 1 review, 10000 reviews
When? Architecture Boundaries
App (Front End)
App (Business Logic)
DB 1
DB 2
Service 1
Service 1
Service 1
Any time the app reaches out for data is a good candidate for dependency injection.
In this scenario, the clients we use to wrap the 2 databases and the 3 services
would each implement an interface that could be mocked for unit tests
When? Responsibility Boundaries
• Fandango Desktop/Mobile Web
– Reviews (Direct DB calls, Elastic search service)
– Movies (DB calls, movie service)
– Theaters (DB calls, Commerce service, old service,
new API)
DI via Delegates
• Initial Effort is low
– No extra frameworks
– unit test can define the mocked method
• Subsequent efforts are O(N)
– One change per new mocked method
• Pros
– Methods can be incorporated one at a time
• Cons
– Each new method will require its own delegate and
new wiring.
DI via Mock POCOs
• Initial Effort is medium
– New class for each mock
– Logic for mock states
• Subsequent efforts
– Potential for new forks (and bugs) in mock POCO logic for
each use case
• Pros
– Don’t need to learn a new framework.
• Cons
– Supporting all use cases increases potential for bugs in the
mocks.
– Some dependencies can’t be mocked
1
1 – With Moq, you can only mock methods defined in an interface or virtual methods.
DI with Mocks (Moq)
• Initial Effort is high
– Each unit test use case requires its own moq wrapper
per dependency
• Subsequent changes
– Only changes to the contract require modifications to
your mocks
• Pros
– Each tests clearly identifies its assumptions
• Cons
– Lots of unit test code will just be setting up the
dependency
Legacy Code: Static Methods
• Interfaces can’t have static methods
• Convert static methods to instance methods
that conform to the (new) interface with a
Singleton to expose the static instance.
Scenario
Production issue with unknown cause
• Scenario in production we can’t reproduce
easily
• In a unit test, mock the underlying interface to
the throw the same exception.
– At the very least, we’ll know how to stop this error
from crashing the entire app and set up proper
logging to identify potential causes
Scenario
Production issue with unknown cause
[Fact]
public void TestIndex_WebExceptionFromReviewManager()
{
InjectCookieCollectionDependency();
var mock = new Mock<IReviewManager>();
mock.Setup(rm => rm.GetEsReviewsByMovie(
It.IsAny<int>(),
It.IsAny<int>(),
It.IsAny<int>(),
It.IsAny<UserReviewSort>()))
.Throws(new WebException());
IReviewManager reviewManager = mock.Object;
using (var controller = new MovieController(reviewManager) { ControllerContext = new ControllerContext { HttpContext = new
MockHttpContext() } })
{
MockHttpContext httpContext = configureContext(UserAgentValue);
controller.ControllerContext.HttpContext = httpContext;
ActionResult result = controller.Index(MovieIdAmericanBeauty);
Assert.IsType(typeof (ViewResult), result);
}
}
Scenario
Anonymous + authenticated users
• Our apps identify a logged in user by the
presence of a cookie. We can mock that!
– See changes to MovieController with
ICustomerCookieProvider
Strategies for Unit Testing
• New Projects
– TDD allows us to work with QA to identify good
test cases before we start writing code
• Legacy Projects
– Don’t test something that’s been working in
production for years
– Create unit tests to reproduce your bug. This will
allow for immediate ROI on the tests
– Introduce tests for new features
Side Effect (Good)
• Enforces the SOLID principles
Single Responsibility [link]
If an interface crosses domains, you know to split them
Multiple interfaces  too many responsibilities for the class
Open/Closed Principle [link]
Your code is inherently open to extension
Liskov Substitution Principle [link]
Your mocks provide are substituted for the concrete
implementations without code changes
Interface segregation Principle [link]
Interface contract hides helper methods
Dependency inversion principle [link]
This is what we’re talking about here
Further Reading
• Martin Fowler (http://martinfowler.com/articles/injection.html)
• AutoFac IoC container(http://autofac.org/)
• AutoFac in actionNuGet Gallery – DI by Environment

More Related Content

What's hot

Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Dror Helper
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingJoe Tremblay
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit testEugenio Lentini
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven DevelopmentPablo Villar
 
Writing Testable Code
Writing Testable CodeWriting Testable Code
Writing Testable Codejameshalsall
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)Foyzul Karim
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitweili_at_slideshare
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testingsgleadow
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testingikhwanhayat
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And MockingJoe Wilson
 
Node.js exception handling
Node.js exception handlingNode.js exception handling
Node.js exception handlingMinh Hoang
 
Unit testing
Unit testing Unit testing
Unit testing dubbu
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android ApplicationsRody Middelkoop
 

What's hot (20)

Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Nunit
NunitNunit
Nunit
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven Development
 
Testing 101
Testing 101Testing 101
Testing 101
 
Nunit
NunitNunit
Nunit
 
Writing Testable Code
Writing Testable CodeWriting Testable Code
Writing Testable Code
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnit
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testing
 
Unit test
Unit testUnit test
Unit test
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Unit Testing 101
Unit Testing 101Unit Testing 101
Unit Testing 101
 
Node.js exception handling
Node.js exception handlingNode.js exception handling
Node.js exception handling
 
Unit testing
Unit testing Unit testing
Unit testing
 
Unit Testing Your Application
Unit Testing Your ApplicationUnit Testing Your Application
Unit Testing Your Application
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 

Viewers also liked

Command-line tools en PHP - deSymfony 2013
Command-line tools en PHP - deSymfony 2013Command-line tools en PHP - deSymfony 2013
Command-line tools en PHP - deSymfony 2013Adán Lobato Lorenzo
 
Diapositivas Spring Framework- Javier Oliver Fulguera
Diapositivas Spring Framework-  Javier Oliver FulgueraDiapositivas Spring Framework-  Javier Oliver Fulguera
Diapositivas Spring Framework- Javier Oliver FulgueraJavier Oliver Fulguera
 
IT 이노베이션 센터 이야기 - AWS Lambda를 활용한 개발 스폰서십 확보편
IT 이노베이션 센터 이야기 - AWS Lambda를 활용한 개발 스폰서십 확보편IT 이노베이션 센터 이야기 - AWS Lambda를 활용한 개발 스폰서십 확보편
IT 이노베이션 센터 이야기 - AWS Lambda를 활용한 개발 스폰서십 확보편Darion Kim
 
주니어 개발자도 이해 할 수 있는 의존성 주입(Dependency Injection)
주니어 개발자도 이해 할 수 있는 의존성 주입(Dependency Injection)주니어 개발자도 이해 할 수 있는 의존성 주입(Dependency Injection)
주니어 개발자도 이해 할 수 있는 의존성 주입(Dependency Injection)Darion Kim
 
[JWPA-1]의존성 주입(Dependency injection)
[JWPA-1]의존성 주입(Dependency injection)[JWPA-1]의존성 주입(Dependency injection)
[JWPA-1]의존성 주입(Dependency injection)Young-Ho Cho
 

Viewers also liked (8)

Command-line tools en PHP - deSymfony 2013
Command-line tools en PHP - deSymfony 2013Command-line tools en PHP - deSymfony 2013
Command-line tools en PHP - deSymfony 2013
 
Proceso de Diseño
Proceso de DiseñoProceso de Diseño
Proceso de Diseño
 
12 dependency injection
12 dependency injection12 dependency injection
12 dependency injection
 
Diapositivas Spring Framework- Javier Oliver Fulguera
Diapositivas Spring Framework-  Javier Oliver FulgueraDiapositivas Spring Framework-  Javier Oliver Fulguera
Diapositivas Spring Framework- Javier Oliver Fulguera
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
IT 이노베이션 센터 이야기 - AWS Lambda를 활용한 개발 스폰서십 확보편
IT 이노베이션 센터 이야기 - AWS Lambda를 활용한 개발 스폰서십 확보편IT 이노베이션 센터 이야기 - AWS Lambda를 활용한 개발 스폰서십 확보편
IT 이노베이션 센터 이야기 - AWS Lambda를 활용한 개발 스폰서십 확보편
 
주니어 개발자도 이해 할 수 있는 의존성 주입(Dependency Injection)
주니어 개발자도 이해 할 수 있는 의존성 주입(Dependency Injection)주니어 개발자도 이해 할 수 있는 의존성 주입(Dependency Injection)
주니어 개발자도 이해 할 수 있는 의존성 주입(Dependency Injection)
 
[JWPA-1]의존성 주입(Dependency injection)
[JWPA-1]의존성 주입(Dependency injection)[JWPA-1]의존성 주입(Dependency injection)
[JWPA-1]의존성 주입(Dependency injection)
 

Similar to Dependency Injection in .NET applications

Visual Automation Framework via Screenshot Comparison
Visual Automation Framework via Screenshot ComparisonVisual Automation Framework via Screenshot Comparison
Visual Automation Framework via Screenshot ComparisonMek Srunyu Stittri
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testabilitydrewz lin
 
DevOps - Boldly Go for Distro
DevOps - Boldly Go for DistroDevOps - Boldly Go for Distro
DevOps - Boldly Go for DistroPaul Boos
 
Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleMock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleP Heinonen
 
Bridging the communication Gap & Continuous Delivery
Bridging the communication Gap & Continuous DeliveryBridging the communication Gap & Continuous Delivery
Bridging the communication Gap & Continuous Deliverymasoodjan
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeAleksandar Bozinovski
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfBruceLee275640
 
Justin Ison
Justin IsonJustin Ison
Justin IsonCodeFest
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 
Automated Exploratory Testing
Automated Exploratory TestingAutomated Exploratory Testing
Automated Exploratory TestingJustin Ison
 
Automated Generation, Evolution and Maintenance: a perspective for mobile GUI...
Automated Generation, Evolution and Maintenance: a perspective for mobile GUI...Automated Generation, Evolution and Maintenance: a perspective for mobile GUI...
Automated Generation, Evolution and Maintenance: a perspective for mobile GUI...Riccardo Coppola
 
Testing Big in JavaScript
Testing Big in JavaScriptTesting Big in JavaScript
Testing Big in JavaScriptRobert DeLuca
 
Building Maintainable Android Apps (DroidCon NYC 2014)
Building Maintainable Android Apps (DroidCon NYC 2014)Building Maintainable Android Apps (DroidCon NYC 2014)
Building Maintainable Android Apps (DroidCon NYC 2014)Kevin Schultz
 
Implementing Quality on a Java Project
Implementing Quality on a Java ProjectImplementing Quality on a Java Project
Implementing Quality on a Java ProjectVincent Massol
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 

Similar to Dependency Injection in .NET applications (20)

Visual Automation Framework via Screenshot Comparison
Visual Automation Framework via Screenshot ComparisonVisual Automation Framework via Screenshot Comparison
Visual Automation Framework via Screenshot Comparison
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
DevOps - Boldly Go for Distro
DevOps - Boldly Go for DistroDevOps - Boldly Go for Distro
DevOps - Boldly Go for Distro
 
Mock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion PrincipleMock Objects, Design and Dependency Inversion Principle
Mock Objects, Design and Dependency Inversion Principle
 
Bridging the communication Gap & Continuous Delivery
Bridging the communication Gap & Continuous DeliveryBridging the communication Gap & Continuous Delivery
Bridging the communication Gap & Continuous Delivery
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable Code
 
Unit Tests with Microsoft Fakes
Unit Tests with Microsoft FakesUnit Tests with Microsoft Fakes
Unit Tests with Microsoft Fakes
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdf
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Coding Naked
Coding NakedCoding Naked
Coding Naked
 
Justin Ison
Justin IsonJustin Ison
Justin Ison
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Automated Exploratory Testing
Automated Exploratory TestingAutomated Exploratory Testing
Automated Exploratory Testing
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
Automated Generation, Evolution and Maintenance: a perspective for mobile GUI...
Automated Generation, Evolution and Maintenance: a perspective for mobile GUI...Automated Generation, Evolution and Maintenance: a perspective for mobile GUI...
Automated Generation, Evolution and Maintenance: a perspective for mobile GUI...
 
Testing Big in JavaScript
Testing Big in JavaScriptTesting Big in JavaScript
Testing Big in JavaScript
 
Building Maintainable Android Apps (DroidCon NYC 2014)
Building Maintainable Android Apps (DroidCon NYC 2014)Building Maintainable Android Apps (DroidCon NYC 2014)
Building Maintainable Android Apps (DroidCon NYC 2014)
 
Implementing Quality on a Java Project
Implementing Quality on a Java ProjectImplementing Quality on a Java Project
Implementing Quality on a Java Project
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 

Recently uploaded

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 ...OnePlan Solutions
 
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.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
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...ICS
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 

Recently uploaded (20)

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 ...
 
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
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
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
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
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...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 

Dependency Injection in .NET applications

  • 1. Dependency Injection with .NET -OR- So you’ve decided to finally inject your dependencies -OR- Let’s test production scenarios so it doesn’t break
  • 2. Overview • What is DI? • Why use DI? • Where to use DI? • How to do DI? • C#, Legacy Code, and DI – Interfaces, and Singletons, and Mocks, oh my!
  • 3. What is Dependency Injection • A software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. – Wikipedia AppIoC Dependency Concrete Implementation Concrete Implementation Concrete Implementation
  • 4. Dependency Inject – An Example • Legacy code w/o DI public class ReviewManager{ public ElasticSearchBackedReviewRepository ReviewsRepo {get; set;} public void GetReviewsByMovie( int movieId){ return ElasticSearchBackedReviewRepository.GetReviews(movieId); } } • Legacy code w/o DI public class ReviewManager{ public IReviewRepository ReviewsRepo {get; set;} Public ReviewManager( IReviewRepository repo ){ ReviewsRepo = repo; } public void GetReviewsByMovie( int movieId){ return ReviewsRepo.GetReviews(moviedId); } } AppIoC Dependency Concrete Implementation Concrete Implementation Concrete Implementation
  • 5. Why Interfaces? • Develop against a contract – Business logic isn’t changed as new implementations are introduced • Moq (for unit tests) requires interfaces or virtual methods. • All wiring for dependencies can be performed in a centralized location
  • 6. Why Mocking? • Allows testing any use case without the need for test data – Mock a response that returns the use case you are testing (as opposed to test data in the DB) – Null return values – Timeout (web service clients) – 0 reviews, 1 review, 10000 reviews
  • 7. When? Architecture Boundaries App (Front End) App (Business Logic) DB 1 DB 2 Service 1 Service 1 Service 1 Any time the app reaches out for data is a good candidate for dependency injection. In this scenario, the clients we use to wrap the 2 databases and the 3 services would each implement an interface that could be mocked for unit tests
  • 8. When? Responsibility Boundaries • Fandango Desktop/Mobile Web – Reviews (Direct DB calls, Elastic search service) – Movies (DB calls, movie service) – Theaters (DB calls, Commerce service, old service, new API)
  • 9. DI via Delegates • Initial Effort is low – No extra frameworks – unit test can define the mocked method • Subsequent efforts are O(N) – One change per new mocked method • Pros – Methods can be incorporated one at a time • Cons – Each new method will require its own delegate and new wiring.
  • 10. DI via Mock POCOs • Initial Effort is medium – New class for each mock – Logic for mock states • Subsequent efforts – Potential for new forks (and bugs) in mock POCO logic for each use case • Pros – Don’t need to learn a new framework. • Cons – Supporting all use cases increases potential for bugs in the mocks. – Some dependencies can’t be mocked 1 1 – With Moq, you can only mock methods defined in an interface or virtual methods.
  • 11. DI with Mocks (Moq) • Initial Effort is high – Each unit test use case requires its own moq wrapper per dependency • Subsequent changes – Only changes to the contract require modifications to your mocks • Pros – Each tests clearly identifies its assumptions • Cons – Lots of unit test code will just be setting up the dependency
  • 12. Legacy Code: Static Methods • Interfaces can’t have static methods • Convert static methods to instance methods that conform to the (new) interface with a Singleton to expose the static instance.
  • 13. Scenario Production issue with unknown cause • Scenario in production we can’t reproduce easily • In a unit test, mock the underlying interface to the throw the same exception. – At the very least, we’ll know how to stop this error from crashing the entire app and set up proper logging to identify potential causes
  • 14. Scenario Production issue with unknown cause [Fact] public void TestIndex_WebExceptionFromReviewManager() { InjectCookieCollectionDependency(); var mock = new Mock<IReviewManager>(); mock.Setup(rm => rm.GetEsReviewsByMovie( It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<UserReviewSort>())) .Throws(new WebException()); IReviewManager reviewManager = mock.Object; using (var controller = new MovieController(reviewManager) { ControllerContext = new ControllerContext { HttpContext = new MockHttpContext() } }) { MockHttpContext httpContext = configureContext(UserAgentValue); controller.ControllerContext.HttpContext = httpContext; ActionResult result = controller.Index(MovieIdAmericanBeauty); Assert.IsType(typeof (ViewResult), result); } }
  • 15. Scenario Anonymous + authenticated users • Our apps identify a logged in user by the presence of a cookie. We can mock that! – See changes to MovieController with ICustomerCookieProvider
  • 16. Strategies for Unit Testing • New Projects – TDD allows us to work with QA to identify good test cases before we start writing code • Legacy Projects – Don’t test something that’s been working in production for years – Create unit tests to reproduce your bug. This will allow for immediate ROI on the tests – Introduce tests for new features
  • 17. Side Effect (Good) • Enforces the SOLID principles Single Responsibility [link] If an interface crosses domains, you know to split them Multiple interfaces  too many responsibilities for the class Open/Closed Principle [link] Your code is inherently open to extension Liskov Substitution Principle [link] Your mocks provide are substituted for the concrete implementations without code changes Interface segregation Principle [link] Interface contract hides helper methods Dependency inversion principle [link] This is what we’re talking about here
  • 18. Further Reading • Martin Fowler (http://martinfowler.com/articles/injection.html) • AutoFac IoC container(http://autofac.org/) • AutoFac in actionNuGet Gallery – DI by Environment

Editor's Notes

  1. See Beyond Compare saved session #1