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

Mais conteúdo relacionado

Mais procurados

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 JestBen McCormick
 
Chegg - iOS @ Scale
Chegg - iOS @ ScaleChegg - iOS @ Scale
Chegg - iOS @ ScaleAviel Lazar
 
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 2019Grzegorz Miejski
 
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 ThymeleafFrank 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 TestingSteven Smith
 
The Python in the Apple
The Python in the AppleThe Python in the Apple
The Python in the ApplezeroSteiner
 
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...
Олександр Хотемський “ProtractorJS як інструмент браузерної автоматизації для...Dakiry
 
Before you jump into Angular
Before you jump into AngularBefore you jump into Angular
Before you jump into AngularM A Hossain Tonu
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0Ganesh Kondal
 
Getting Started with ASP.NET 5
Getting Started with ASP.NET 5Getting Started with ASP.NET 5
Getting Started with ASP.NET 5Brij 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 FasterBrij Mishra
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Ganesh 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 ProtractorKasun Kodagoda
 
Rest API Testing
Rest API TestingRest API Testing
Rest API Testingupadhyay_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...GoQA
 
Hibernate performance tuning
Hibernate performance tuningHibernate performance tuning
Hibernate performance tuningMikalai 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 codeMichal Juhas
 

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

Semelhante a Introduction to Dependency Injection (DI) and Inversion of Control (IoC

springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfBruceLee275640
 
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 ToolsWilliam Simms
 
Getting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesGetting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesAmazon 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 TestingTim 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 TestingSteven 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 Autofacmeghantaylor
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with SeleniumDave 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 CodeAleksandar Bozinovski
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuPhat 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 2014FalafelSoftware
 
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, cicon2010Joel 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 Molieremfrancis
 
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 2016Steven Smith
 

Semelhante a Introduction to Dependency Injection (DI) and Inversion of Control (IoC (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
 

Mais de 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 FrameworkSolTech, 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 StepsSolTech, Inc.
 
Empowering Your Job Search: 10 Tips
Empowering Your Job Search: 10 TipsEmpowering Your Job Search: 10 Tips
Empowering Your Job Search: 10 TipsSolTech, Inc.
 
Responsive Web Design using ZURB Foundation
Responsive Web Design using ZURB FoundationResponsive Web Design using ZURB Foundation
Responsive Web Design using ZURB FoundationSolTech, Inc.
 
Getting started with Xamarin forms
Getting started with Xamarin formsGetting started with Xamarin forms
Getting started with Xamarin formsSolTech, Inc.
 
Debugging Javascript
Debugging JavascriptDebugging Javascript
Debugging JavascriptSolTech, Inc.
 
SolTech's The Constantly Connected Customer
SolTech's The Constantly Connected CustomerSolTech's The Constantly Connected Customer
SolTech's The Constantly Connected CustomerSolTech, Inc.
 

Mais de 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
 

Último

Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...tanu pandey
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts servicesonalikaur4
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Standkumarajju5765
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...aditipandeya
 
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...sonatiwari757
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsThierry TROUIN ☁
 
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...Neha Pandey
 
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.soniya singh
 
On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024APNIC
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirtrahman018755
 
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.soniya singh
 
SEO Growth Program-Digital optimization Specialist
SEO Growth Program-Digital optimization SpecialistSEO Growth Program-Digital optimization Specialist
SEO Growth Program-Digital optimization SpecialistKHM Anwar
 
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Delhi Call girls
 
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663Call Girls Mumbai
 
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl ServiceRussian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl Servicegwenoracqe6
 
Radiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsRadiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsstephieert
 

Último (20)

Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
 
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with Flows
 
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
 
Call Girls In Noida 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In Noida 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICECall Girls In Noida 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In Noida 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
 
On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
 
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
 
SEO Growth Program-Digital optimization Specialist
SEO Growth Program-Digital optimization SpecialistSEO Growth Program-Digital optimization Specialist
SEO Growth Program-Digital optimization Specialist
 
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
 
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
 
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl ServiceRussian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
 
Radiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsRadiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girls
 

Introduction to Dependency Injection (DI) and Inversion of Control (IoC

  • 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