SlideShare a Scribd company logo
INTRODUCTION TO
DEPENDENCY INJECTION
What is this thing?
• Dependency Injection (also called Inversion of Control) is a technique for
providing the things your code needs at runtime.
• Relies very heavily on abstraction layers (interfaces, base classes)
• When used properly, can make your code simpler and easier to test!
Let’s Start at the Beginning
public class MyBusinessLogic
{
public MyBusinessLogic()
{
}
public void DoesSomethingInteresting(MyDataItem item)
{
MyDataAccessLayer foo = new MyDataAccessLayer();
foo.AddItem(item);
}
}
Why is this a problem?
• It ties us to a particular data access layer
• What if I want to be able to support a different database engine?
• What if I want to use a Web Service?
• Etc.
• It’s hard to test
• I can’t verify the code works unless I have a database
• It takes time to set the database up
• What happens when more than one person wants to run a test at the same time?
How can we fix this?
• Instead of hard-coding the use of MyDataAccessLayer let’s make things
more flexible
• Define a new interface: IMyDataAccessLayer
• Visual Studio makes this pretty easy; right-click the class and choose “Extract Interface
• Use this interface instead of the concrete class
How can we fix this (contd.)?
public class MyBusinessLogic
{
IMyDataAccessLayer _myDAL;
public MyBusinessLogic(IMyDataAccessLayer myDAL)
{
_myDAL = myDAL;
}
public void DoesSomethingInteresting(MyDataItem item)
{
_myDAL.AddItem(item);
}
}
How can we get this into our class?
• Simplest way: supplying it to the constructor (aka Constructor injection)
• This works, but isn’t much better than the original
• Better way: use a Dependency Injection Container
• Unity
• Ninject
• SimpleIOC
• etc.
var myBLL = new MyBusinessLogic(new MyDataAccessLayer)
Using a DI Container
• Most containers use a registration mechanism mapping type-to-type:
• Resolve types at runtime:
myContainer.RegisterType(typeof(IFoo), typeof(Foo))
myContainer.RegisterType<IFoo, Foo>()
var instance = myContainer.Resolve(typeof(IFoo))
var instance = myContainer.Resolve<IFoo>()
But wait, there’s more!
• Every DI container supports dependency chains
• If registered type A takes an instance of registered type B as a constructor argument, then
an instance of B will be automatically created:
• Many frameworks use DI containers to automatically resolve types
• For example, ASP.NET MVC’s Dependency Resolver
• NuGet makes this very easy - Unity bootstrapper
myContainer.RegisterType<IMyBusinessLogic, MyBusinessLogic>();
myContainer.RegisterType<IMyDataAccessLayer, MyDataAccessLayer>();
var myBLL = myContainer.Resolve(IMyBusinessLogic);
DEMO: ASP.NET MVC
Passing a controller an instance of a service
Where does “testable” come in?
• Classes that take dependencies as configuration are much easier to test!
• This is where the abstraction layer comes in very handy!
• Rather than supply that dependency, pass something that looks like it.
• Simplest approach: derive a “fake” class from the base class/interface
• Better approach: use a mocking framework like Moq!
• Code/configure your fake to behave the way you expect it to, and assert that
*your* code behaves as it should.
The concept:
• The two-port model
• For a given input, you expect a certain output
Your CodeInput Output
DEMO: USING MOQ IN A UNIT TEST
Verifying that the controller does what it should
What else can we do with this?
• Once you start thinking in terms of dependencies, you can start making your
code a LOT cleaner.
• AKA “Separation of Concerns” – have classes that do one type of thing and have other
classes use them as Lego blocks to build complex systems.
• Deliver your code faster
• Defining the “contract” in terms of interfaces and expected behavior allows different people
to work in parallel!
• Make your own code easier to maintain
• If each class has its own job, and you have interfaces defining the API, you can change
implementations without modifying the calling code
• Instead of writing one-off test apps, write unit tests
Stupid Container Tricks
• Lifetime Management
• LifetimeManager
• A way to create a singleton from any class
• Named registrations
• RegisterType<T>(“Name”)
• ResolveAll<T>()
• Can be used as an extensibility point – “plugins”
• XML Configuration
• Rather than declaring everything in code, use an XML file
• Discovery
• Use reflection to find all types that implement a given interface and register them
• Microsoft Extensibility Framework
References
• Microsoft Unity
• https://unity.codeplex.com/
• “Dependency Injection with Unity”
http://www.microsoft.com/en-us/download/details.aspx?id=39944
• Moq
• https://github.com/Moq/moq4
QUESTIONS?
Thank you for attending!

More Related Content

What's hot

Icon UK 2018 - Spring forward: an introduction to Spring boot and Thymeleaf f...
Icon UK 2018 - Spring forward: an introduction to Spring boot and Thymeleaf f...Icon UK 2018 - Spring forward: an introduction to Spring boot and Thymeleaf f...
Icon UK 2018 - Spring forward: an introduction to Spring boot and Thymeleaf f...
Frank van der Linden
 
Saving Time By Testing With Jest
Saving Time By Testing With JestSaving Time By Testing With Jest
Saving Time By Testing With Jest
Ben McCormick
 
Chegg - iOS @ Scale
Chegg - iOS @ ScaleChegg - iOS @ Scale
Chegg - iOS @ Scale
Aviel Lazar
 
Lecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 SlideLecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 Slide
Kobkrit Viriyayudhakorn
 
Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019
Grzegorz Miejski
 
Uklug2012 yellow and blue stream
Uklug2012 yellow and blue streamUklug2012 yellow and blue stream
Uklug2012 yellow and blue stream
Frank van der Linden
 
Spring forward: an introduction to Spring boot and Thymeleaf
Spring forward: an introduction to Spring boot and ThymeleafSpring forward: an introduction to Spring boot and Thymeleaf
Spring forward: an introduction to Spring boot and Thymeleaf
Frank van der Linden
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
Steven Smith
 
The Python in the Apple
The Python in the AppleThe Python in the Apple
The Python in the Apple
zeroSteiner
 
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...
Dakiry
 
Before you jump into Angular
Before you jump into AngularBefore you jump into Angular
Before you jump into Angular
M A Hossain Tonu
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0
Ganesh Kondal
 
Getting Started with ASP.NET 5
Getting Started with ASP.NET 5Getting Started with ASP.NET 5
Getting Started with ASP.NET 5
Brij Mishra
 
10 tips to make your ASP.NET Apps Faster
10 tips to make your ASP.NET Apps Faster10 tips to make your ASP.NET Apps Faster
10 tips to make your ASP.NET Apps Faster
Brij Mishra
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
Ganesh Kondal
 
Better End-to-End Testing with Page Objects Model using Protractor
Better End-to-End Testing with Page Objects Model using ProtractorBetter End-to-End Testing with Page Objects Model using Protractor
Better End-to-End Testing with Page Objects Model using Protractor
Kasun Kodagoda
 
Rest API Testing
Rest API TestingRest API Testing
Rest API Testing
upadhyay_25
 
КОСТЯНТИН КЛЮЄВ «Postman: API Automation Testing Swiss Army Knife» Kyiv QADay...
КОСТЯНТИН КЛЮЄВ «Postman: API Automation Testing Swiss Army Knife» Kyiv QADay...КОСТЯНТИН КЛЮЄВ «Postman: API Automation Testing Swiss Army Knife» Kyiv QADay...
КОСТЯНТИН КЛЮЄВ «Postman: API Automation Testing Swiss Army Knife» Kyiv QADay...
QADay
 
Hibernate performance tuning
Hibernate performance tuningHibernate performance tuning
Hibernate performance tuning
Mikalai Alimenkou
 
PHP Frameworks, or how I learnt to stop worrying and love the code
PHP Frameworks, or how I learnt to stop worrying and love the codePHP Frameworks, or how I learnt to stop worrying and love the code
PHP Frameworks, or how I learnt to stop worrying and love the code
Michal Juhas
 

What's hot (20)

Icon UK 2018 - Spring forward: an introduction to Spring boot and Thymeleaf f...
Icon UK 2018 - Spring forward: an introduction to Spring boot and Thymeleaf f...Icon UK 2018 - Spring forward: an introduction to Spring boot and Thymeleaf f...
Icon UK 2018 - Spring forward: an introduction to Spring boot and Thymeleaf f...
 
Saving Time By Testing With Jest
Saving Time By Testing With JestSaving Time By Testing With Jest
Saving Time By Testing With Jest
 
Chegg - iOS @ Scale
Chegg - iOS @ ScaleChegg - iOS @ Scale
Chegg - iOS @ Scale
 
Lecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 SlideLecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 Slide
 
Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019
 
Uklug2012 yellow and blue stream
Uklug2012 yellow and blue streamUklug2012 yellow and blue stream
Uklug2012 yellow and blue stream
 
Spring forward: an introduction to Spring boot and Thymeleaf
Spring forward: an introduction to Spring boot and ThymeleafSpring forward: an introduction to Spring boot and Thymeleaf
Spring forward: an introduction to Spring boot and Thymeleaf
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
The Python in the Apple
The Python in the AppleThe Python in the Apple
The Python in the Apple
 
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...
 
Before you jump into Angular
Before you jump into AngularBefore you jump into Angular
Before you jump into Angular
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0
 
Getting Started with ASP.NET 5
Getting Started with ASP.NET 5Getting Started with ASP.NET 5
Getting Started with ASP.NET 5
 
10 tips to make your ASP.NET Apps Faster
10 tips to make your ASP.NET Apps Faster10 tips to make your ASP.NET Apps Faster
10 tips to make your ASP.NET Apps Faster
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
 
Better End-to-End Testing with Page Objects Model using Protractor
Better End-to-End Testing with Page Objects Model using ProtractorBetter End-to-End Testing with Page Objects Model using Protractor
Better End-to-End Testing with Page Objects Model using Protractor
 
Rest API Testing
Rest API TestingRest API Testing
Rest API Testing
 
КОСТЯНТИН КЛЮЄВ «Postman: API Automation Testing Swiss Army Knife» Kyiv QADay...
КОСТЯНТИН КЛЮЄВ «Postman: API Automation Testing Swiss Army Knife» Kyiv QADay...КОСТЯНТИН КЛЮЄВ «Postman: API Automation Testing Swiss Army Knife» Kyiv QADay...
КОСТЯНТИН КЛЮЄВ «Postman: API Automation Testing Swiss Army Knife» Kyiv QADay...
 
Hibernate performance tuning
Hibernate performance tuningHibernate performance tuning
Hibernate performance tuning
 
PHP Frameworks, or how I learnt to stop worrying and love the code
PHP Frameworks, or how I learnt to stop worrying and love the codePHP Frameworks, or how I learnt to stop worrying and love the code
PHP Frameworks, or how I learnt to stop worrying and love the code
 

Similar to Introduction to Dependency Injection

springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdf
BruceLee275640
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®
Hannes Lowette
 
Unit Testing and Tools
Unit Testing and ToolsUnit Testing and Tools
Unit Testing and Tools
William Simms
 
Getting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesGetting Started with Serverless Architectures
Getting Started with Serverless Architectures
Amazon Web Services
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®
Hannes Lowette
 
The Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To TestingThe Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To Testing
Tim Duckett
 
NCUG 2019: Spring forward: an introduction to Spring boot and Thymeleaf for (...
NCUG 2019: Spring forward: an introduction to Spring boot and Thymeleaf for (...NCUG 2019: Spring forward: an introduction to Spring boot and Thymeleaf for (...
NCUG 2019: Spring forward: an introduction to Spring boot and Thymeleaf for (...
Frank van der Linden
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
Steven Smith
 
The Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOCCarl Lu
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
meghantaylor
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with Selenium
Dave Haeffner
 
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
Aleksandar Bozinovski
 
Unit Tests with Microsoft Fakes
Unit Tests with Microsoft FakesUnit Tests with Microsoft Fakes
Unit Tests with Microsoft Fakes
Aleksandar Bozinovski
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
Phat VU
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
FalafelSoftware
 
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...seleniumconf
 
CodeIgniter for Startups, cicon2010
CodeIgniter for Startups, cicon2010CodeIgniter for Startups, cicon2010
CodeIgniter for Startups, cicon2010
Joel Gascoigne
 
Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)
Igalia
 
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
mfrancis
 
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Steven Smith
 

Similar to Introduction to Dependency Injection (20)

springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdf
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®
 
Unit Testing and Tools
Unit Testing and ToolsUnit Testing and Tools
Unit Testing and Tools
 
Getting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesGetting Started with Serverless Architectures
Getting Started with Serverless Architectures
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®
 
The Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To TestingThe Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To Testing
 
NCUG 2019: Spring forward: an introduction to Spring boot and Thymeleaf for (...
NCUG 2019: Spring forward: an introduction to Spring boot and Thymeleaf for (...NCUG 2019: Spring forward: an introduction to Spring boot and Thymeleaf for (...
NCUG 2019: Spring forward: an introduction to Spring boot and Thymeleaf for (...
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
The Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOC
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with Selenium
 
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
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
 
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
 
CodeIgniter for Startups, cicon2010
CodeIgniter for Startups, cicon2010CodeIgniter for Startups, cicon2010
CodeIgniter for Startups, cicon2010
 
Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)
 
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
 
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
 

More from SolTech, Inc.

Responsive Web Design using the Foundation 5 CSS Framework
Responsive Web Design using the Foundation 5 CSS FrameworkResponsive Web Design using the Foundation 5 CSS Framework
Responsive Web Design using the Foundation 5 CSS Framework
SolTech, Inc.
 
How to Rock your Phone Interview: 4 Easy Steps
How to Rock your Phone Interview: 4 Easy StepsHow to Rock your Phone Interview: 4 Easy Steps
How to Rock your Phone Interview: 4 Easy Steps
SolTech, Inc.
 
Empowering Your Job Search: 10 Tips
Empowering Your Job Search: 10 TipsEmpowering Your Job Search: 10 Tips
Empowering Your Job Search: 10 Tips
SolTech, Inc.
 
Responsive Web Design using ZURB Foundation
Responsive Web Design using ZURB FoundationResponsive Web Design using ZURB Foundation
Responsive Web Design using ZURB Foundation
SolTech, Inc.
 
Getting started with Xamarin forms
Getting started with Xamarin formsGetting started with Xamarin forms
Getting started with Xamarin forms
SolTech, Inc.
 
Intro to AngularJs
Intro to AngularJsIntro to AngularJs
Intro to AngularJs
SolTech, Inc.
 
Debugging Javascript
Debugging JavascriptDebugging Javascript
Debugging Javascript
SolTech, Inc.
 
SolTech's The Constantly Connected Customer
SolTech's The Constantly Connected CustomerSolTech's The Constantly Connected Customer
SolTech's The Constantly Connected Customer
SolTech, Inc.
 

More from SolTech, Inc. (8)

Responsive Web Design using the Foundation 5 CSS Framework
Responsive Web Design using the Foundation 5 CSS FrameworkResponsive Web Design using the Foundation 5 CSS Framework
Responsive Web Design using the Foundation 5 CSS Framework
 
How to Rock your Phone Interview: 4 Easy Steps
How to Rock your Phone Interview: 4 Easy StepsHow to Rock your Phone Interview: 4 Easy Steps
How to Rock your Phone Interview: 4 Easy Steps
 
Empowering Your Job Search: 10 Tips
Empowering Your Job Search: 10 TipsEmpowering Your Job Search: 10 Tips
Empowering Your Job Search: 10 Tips
 
Responsive Web Design using ZURB Foundation
Responsive Web Design using ZURB FoundationResponsive Web Design using ZURB Foundation
Responsive Web Design using ZURB Foundation
 
Getting started with Xamarin forms
Getting started with Xamarin formsGetting started with Xamarin forms
Getting started with Xamarin forms
 
Intro to AngularJs
Intro to AngularJsIntro to AngularJs
Intro to AngularJs
 
Debugging Javascript
Debugging JavascriptDebugging Javascript
Debugging Javascript
 
SolTech's The Constantly Connected Customer
SolTech's The Constantly Connected CustomerSolTech's The Constantly Connected Customer
SolTech's The Constantly Connected Customer
 

Recently uploaded

History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
laozhuseo02
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
JeyaPerumal1
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
nirahealhty
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
3ipehhoa
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
laozhuseo02
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
3ipehhoa
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptxInternet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
VivekSinghShekhawat2
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
Rogerio Filho
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Sanjeev Rampal
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Brad Spiegel Macon GA
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
eutxy
 
BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
natyesu
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
Javier Lasa
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
ufdana
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
GTProductions1
 
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
keoku
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
Arif0071
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
Gal Baras
 

Recently uploaded (20)

History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptxInternet-Security-Safeguarding-Your-Digital-World (1).pptx
Internet-Security-Safeguarding-Your-Digital-World (1).pptx
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
 
BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
 
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 

Introduction to Dependency Injection

  • 2. What is this thing? • Dependency Injection (also called Inversion of Control) is a technique for providing the things your code needs at runtime. • Relies very heavily on abstraction layers (interfaces, base classes) • When used properly, can make your code simpler and easier to test!
  • 3. Let’s Start at the Beginning public class MyBusinessLogic { public MyBusinessLogic() { } public void DoesSomethingInteresting(MyDataItem item) { MyDataAccessLayer foo = new MyDataAccessLayer(); foo.AddItem(item); } }
  • 4. Why is this a problem? • It ties us to a particular data access layer • What if I want to be able to support a different database engine? • What if I want to use a Web Service? • Etc. • It’s hard to test • I can’t verify the code works unless I have a database • It takes time to set the database up • What happens when more than one person wants to run a test at the same time?
  • 5. How can we fix this? • Instead of hard-coding the use of MyDataAccessLayer let’s make things more flexible • Define a new interface: IMyDataAccessLayer • Visual Studio makes this pretty easy; right-click the class and choose “Extract Interface • Use this interface instead of the concrete class
  • 6. How can we fix this (contd.)? public class MyBusinessLogic { IMyDataAccessLayer _myDAL; public MyBusinessLogic(IMyDataAccessLayer myDAL) { _myDAL = myDAL; } public void DoesSomethingInteresting(MyDataItem item) { _myDAL.AddItem(item); } }
  • 7. How can we get this into our class? • Simplest way: supplying it to the constructor (aka Constructor injection) • This works, but isn’t much better than the original • Better way: use a Dependency Injection Container • Unity • Ninject • SimpleIOC • etc. var myBLL = new MyBusinessLogic(new MyDataAccessLayer)
  • 8. Using a DI Container • Most containers use a registration mechanism mapping type-to-type: • Resolve types at runtime: myContainer.RegisterType(typeof(IFoo), typeof(Foo)) myContainer.RegisterType<IFoo, Foo>() var instance = myContainer.Resolve(typeof(IFoo)) var instance = myContainer.Resolve<IFoo>()
  • 9. But wait, there’s more! • Every DI container supports dependency chains • If registered type A takes an instance of registered type B as a constructor argument, then an instance of B will be automatically created: • Many frameworks use DI containers to automatically resolve types • For example, ASP.NET MVC’s Dependency Resolver • NuGet makes this very easy - Unity bootstrapper myContainer.RegisterType<IMyBusinessLogic, MyBusinessLogic>(); myContainer.RegisterType<IMyDataAccessLayer, MyDataAccessLayer>(); var myBLL = myContainer.Resolve(IMyBusinessLogic);
  • 10. DEMO: ASP.NET MVC Passing a controller an instance of a service
  • 11. Where does “testable” come in? • Classes that take dependencies as configuration are much easier to test! • This is where the abstraction layer comes in very handy! • Rather than supply that dependency, pass something that looks like it. • Simplest approach: derive a “fake” class from the base class/interface • Better approach: use a mocking framework like Moq! • Code/configure your fake to behave the way you expect it to, and assert that *your* code behaves as it should.
  • 12. The concept: • The two-port model • For a given input, you expect a certain output Your CodeInput Output
  • 13. DEMO: USING MOQ IN A UNIT TEST Verifying that the controller does what it should
  • 14. What else can we do with this? • Once you start thinking in terms of dependencies, you can start making your code a LOT cleaner. • AKA “Separation of Concerns” – have classes that do one type of thing and have other classes use them as Lego blocks to build complex systems. • Deliver your code faster • Defining the “contract” in terms of interfaces and expected behavior allows different people to work in parallel! • Make your own code easier to maintain • If each class has its own job, and you have interfaces defining the API, you can change implementations without modifying the calling code • Instead of writing one-off test apps, write unit tests
  • 15. Stupid Container Tricks • Lifetime Management • LifetimeManager • A way to create a singleton from any class • Named registrations • RegisterType<T>(“Name”) • ResolveAll<T>() • Can be used as an extensibility point – “plugins” • XML Configuration • Rather than declaring everything in code, use an XML file • Discovery • Use reflection to find all types that implement a given interface and register them • Microsoft Extensibility Framework
  • 16. References • Microsoft Unity • https://unity.codeplex.com/ • “Dependency Injection with Unity” http://www.microsoft.com/en-us/download/details.aspx?id=39944 • Moq • https://github.com/Moq/moq4