This document discusses the differences between dependency injection and service locator patterns for inversion of control. It recommends that constructor injection generally be used except for facade classes, loops, base classes, and unknown types, where a service locator may be preferable. An inversion of control container can also automatically manage object creation and dependencies.
Dependency Injection vs Service Locator - Best Practice
1. Dependency Injection vs. Service Locator
- Best Practice
Lars-Erik Kindblad
Senior Consultant
Blog: kindblad.com
2. Agenda
Intro
• Inversion of Control
• Dependency Injection Patterns
• Service Locator Patterns
• Inversion of Control Containers
Best Practice
• What patterns to use
• When to use the patterns
Summary
| Sector, Alliance, Offering
3. Inversion of Control
Inversion of Control = IOC
Make code loosely coupled
Make unit testing possible
How? Move creation of dependencies outside the class they are
being used in
A better name - Inversion of Dependency Creation
| Sector, Alliance, Offering
12. Inversion of Control Container
A framework that can automatically create a given type with all the
required dependencies
Popular frameworks
• Unity
• Castle Windsor
• Ninject
• StructureMap
• etc.
| Sector, Alliance, Offering
13. Inversion of Control Container
Manual approach
Using an IOC Container
| Sector, Alliance, Offering
40. Summary
Constructor Injection Injected Service Locator
Facade classes X
(WCF Services,
MVC Controllers)
Loops X (Func<>) X
Base classes X
Unknown types at X
compile time
All other scenarios X
| Sector, Alliance, Offering