SlideShare ist ein Scribd-Unternehmen logo
1 von 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!

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (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
 

Ähnlich wie Introduction to Dependency Injection

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
 
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 Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOC
Carl Lu
 
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
 

Ähnlich wie 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
 

Mehr von SolTech, Inc.

Mehr von 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
 

Kürzlich hochgeladen

一比一原版犹他大学毕业证如何办理
一比一原版犹他大学毕业证如何办理一比一原版犹他大学毕业证如何办理
一比一原版犹他大学毕业证如何办理
F
 
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
gajnagarg
 
一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理
F
 
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
ayvbos
 
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsRussian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Monica Sydney
 
一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理
F
 
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfpdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
JOHNBEBONYAP1
 
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
ayvbos
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
ydyuyu
 

Kürzlich hochgeladen (20)

Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call GirlsMira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
 
一比一原版犹他大学毕业证如何办理
一比一原版犹他大学毕业证如何办理一比一原版犹他大学毕业证如何办理
一比一原版犹他大学毕业证如何办理
 
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
 
一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理
 
Call girls Service in Ajman 0505086370 Ajman call girls
Call girls Service in Ajman 0505086370 Ajman call girlsCall girls Service in Ajman 0505086370 Ajman call girls
Call girls Service in Ajman 0505086370 Ajman call girls
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
 
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
 
South Bopal [ (Call Girls) in Ahmedabad ₹7.5k Pick Up & Drop With Cash Paymen...
South Bopal [ (Call Girls) in Ahmedabad ₹7.5k Pick Up & Drop With Cash Paymen...South Bopal [ (Call Girls) in Ahmedabad ₹7.5k Pick Up & Drop With Cash Paymen...
South Bopal [ (Call Girls) in Ahmedabad ₹7.5k Pick Up & Drop With Cash Paymen...
 
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsRussian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理
 
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
 
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasBest SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency Dallas
 
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfpdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
 
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
 
Call girls Service Canacona - 8250092165 Our call girls are sure to provide y...
Call girls Service Canacona - 8250092165 Our call girls are sure to provide y...Call girls Service Canacona - 8250092165 Our call girls are sure to provide y...
Call girls Service Canacona - 8250092165 Our call girls are sure to provide y...
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
 
PIC Microcontroller Structure & Assembly Language.ppsx
PIC Microcontroller Structure & Assembly Language.ppsxPIC Microcontroller Structure & Assembly Language.ppsx
PIC Microcontroller Structure & Assembly Language.ppsx
 
Sensual Call Girls in Tarn Taran Sahib { 9332606886 } VVIP NISHA Call Girls N...
Sensual Call Girls in Tarn Taran Sahib { 9332606886 } VVIP NISHA Call Girls N...Sensual Call Girls in Tarn Taran Sahib { 9332606886 } VVIP NISHA Call Girls N...
Sensual Call Girls in Tarn Taran Sahib { 9332606886 } VVIP NISHA Call Girls N...
 

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