SlideShare uma empresa Scribd logo
1 de 32
Baixar para ler offline
Dependency Injection
@ AngularJS
Ran Mizrahi (@ranm8)
Open Source Dpt. Leader @ CodeOasis
Monday, September 9, 13
About CodeOasis
• CodeOasis specializes in cutting-edge web solutions.
• Large variety of customers (from startups to enterprises).
• We LOVE JavaScript (-:
• Technologies we love:
• Symfony2
• AngularJS
• nodeJS
• HTML5
• CSS3
• Our Microsoft department works with C#, WPF, etc.
Monday, September 9, 13
What is Dependency
Injection???
Monday, September 9, 13
The Problem
function SessionStore() {}
SessionStore.prototype = {
set: function(name, value) {
window.localStorage.setItem(name, value);
},
get: function(name) {
return window.localStorage.getItem(name);
}
}
function User() {
this.sessionStore = new SessionStore();
}
User.prototype = {
setSession: function(session) {
this.sessionStore.set('session', session);
},
getSession: function() {
return this.sessionStore.get('session');
}
}
Monday, September 9, 13
The Problem
Everything goes well and the code is working.
But now we have to change the session name...
We can use a global variable:
sessionName = 'newSessionName';
function User() {
this.sessionStore = new SessionStore();
}
// ...
Maybe we should hard-coded pass it to the store:
function User() {
this.sessionStore = new SessionStore('newSessionName');
}
// ...
Monday, September 9, 13
The Problem
How would you change the entire SessionStore
implementation?
Cookies
Server
...
function User() {
this.sessionStore = registry.get('SessionStore');
}
// ...
Should we use some global registry object??
How would we test the User??
Monday, September 9, 13
The Problem
All those solutions are bad because:
• Couples code to one implementation.
• Hard to configure
• Cannot change the implementation without changing the
User prototype.
• Untestable code unless you monkey patch it.
Monday, September 9, 13
Dependency Injection
Dependency injection is a software
design pattern that allows the
removal of hard-coded
dependencies and makes it possible
to change them.
-- Wikipedia
Monday, September 9, 13
Dependency Injection To The Rescue!
Instead of instantiating the SessionStore within the User...
function User(sessionStore) {
this.sessionStore = sessionStore;
}
// ...
var user = new User(new SessionStore());
JUST INJECT IT!!!
Monday, September 9, 13
Advantages Of Using DI
Use different session store strategies...
function User(sessionStore) {
this.sessionStore = sessionStore;
}
// ...
var user = new User(new CookieSessionStore());
Monday, September 9, 13
Advantages Of Using DI
Configuration becomes easy...
function User(sessionStore) {
this.sessionStore = sessionStore;
}
// ...
var user = new User(new SessionStore('mySessionName'));
Monday, September 9, 13
Advantages Of Using DI
Now we can easily mock the SessionStore (for testing
purposes)...
function User(sessionStore) {
this.sessionStore = sessionStore;
}
// ...
var user = new User(new MockSessionStore());
Monday, September 9, 13
All those things makes our code
MAINTAINABLE
because we’ve..
Less code
Extensible
Testable
Monday, September 9, 13
But How To Scale It?!!?!?
But what if we have a slightly more complex application..
And we do that in many different places around our application:
var user = new User(new SessionStore(new
SomeThirdParty(jQuery), new Http(new Thing())), new
Something());
//....
var user = new User(new SessionStore(new
SomeThirdParty(jQuery), new Http(new Thing())), new
Something());
//....
var user = new User(new SessionStore(new
SomeThirdParty(jQuery), new Http(new Thing())), new
Something());
Monday, September 9, 13
Don’t worry!
Monday, September 9, 13
DI Container To The
Rescue
Monday, September 9, 13
DI Container (e.g. Injector, Provider)
• Instantiates objects and their dependencies on demand.
• Allows to configure objects before instantiation.
• Can instantiate new objects on demand or provide existing
ones from cache.
• The objects must never know they are being managed by the
container.
• A container should be able to manage any object.
Monday, September 9, 13
AngularJS DI
Monday, September 9, 13
How The DI Injector Works?!
• Angular inject the requested service by the function argument
names.
• Can also be done with an array.
• Once requested Angular’s injector would instantiate the
requested service and inject it.
angular.module('myModule')
.controller('MyCtrl', MyCtrl);
function MyCtrl($http) {
$http.get('http://google.com').then(getTheMonkey);
}
Monday, September 9, 13
The Array Notation
• Allows minifiers to preserve argument names for the
dependency injection to work with.
• More flexible - Separates dependency declaration from your
unit.
angular.module('myModule')
.controller('MyCtrl', ['$http', MyCtrl]);
function MyCtrl($http) {
$http.get('http://google.com').then(getTheMonkey);
}
Monday, September 9, 13
Changing The Implementation
angular.module('myModule')
.controller('MyCtrl', ['myHttp', MyCtrl])
.factory('myHttp', ['$q', myHttp]);
function myHttp($q) {
return {
get: function() {
var defer = $q.defer();
// Do something with XHR and return a promise...
return defer.promise;
}
};
}
function MyCtrl($http) {
$http.get('http://google.com').then(someCallback);
}
• Changes the implementation by changing only the array
notation.
• Angular’s injector instantiates the dependencies of each
dependency.
Monday, September 9, 13
How Do I Use It?
Monday, September 9, 13
Service/Factory
A service is the Angular way of exposing objects within the
$injector.
• Can have multiple dependencies that will be injected when
invoked.
angular.module('myModule')
.service('myHttp', ['$q', myHttp]);
function myHttp($q) {
this.get = function() {
var defer = $q.defer();
// Do something with XHR and return a promise...
return defer.promise;
};
}
Monday, September 9, 13
Factory
Shorthand for registering services without a constructor
function (assigned to $get property directly).
angular.module('myModule')
.factory('myHttp', ['$q', myHttp]);
function myHttp($q) {
return {
get: function() {
var defer = $q.defer();
// Do something with XHR and return a promise...
return defer.promise;
}
};
}
Monday, September 9, 13
Provider
Registers a provider to a service.
• Allows the save configuration state to the service.
• Only constants can be injected.
• The provider is a constructor function.
• $get is a function that returns the actual service.
Monday, September 9, 13
Provider
angular.module('myModule')
.provider('myHttp', myHttp);
function myHttp() {
var baseUrl;
this.baseUrl = function(value) {
if (!value) {
return baseUrl;
}
baseUrl = value;
};
this.$get = ['$q', function() {
// myHttp service implementation...
}];
}
Monday, September 9, 13
Configuration Phase vs. Run Phase
Configuration Phase
Run Phase
• Runs before any service was instantiated.
• Only providers can be injected.
• Each provider is injected with the “Provider” suffix (e.g.
$locationProvider)
• Allows to purely configure the services state.
• Services state should be not be changed now (already
configured during run phase).
• Providers now cannot be injected.
Monday, September 9, 13
Config
Use the service providers to configure the services state
during the config phase to the run phase.
angular.module('myModule')
.config(['myHttpProvider', '$locationProvider', appConfig]);
function appConfig(myHttpProvider, $locationProvider) {
// Configure app to use HTML5 History API..
$locationProvider.html5Mode(true);
// Configure my service baseUrl..
myHttpProvider.baseUrl('http://www.example.com');
}
Monday, September 9, 13
Value
Value is a shorthand to register a simple value as a service.
angular.module('myModule')
.value('myHttp', 'some string');
Monday, September 9, 13
Constant
Constant is the same as value, but unlike value it can be
injected to configuration function
angular.module('myModule')
.constant('someConstant', '123');
Monday, September 9, 13
Angular’s DI In Testing
describe('myHttp', function() {
var mockQ = {
then: function(){}
},
http;
beforeEach(module(function($provide) {
$provide.value('$q', mockQ);
}));
beforeEach(inject(function(myHttp) {
http = myHttp;
}));
describe('#get()', function() {
it('should return a promise', function() {
// test your code here
});
});
});
Monday, September 9, 13
Questions?
Thank you!
Monday, September 9, 13

Mais conteúdo relacionado

Mais procurados

AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developers
Kai Koenig
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 

Mais procurados (20)

Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
 
Workshop 3: JavaScript build tools
Workshop 3: JavaScript build toolsWorkshop 3: JavaScript build tools
Workshop 3: JavaScript build tools
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and Performance
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
 
Building a Startup Stack with AngularJS
Building a Startup Stack with AngularJSBuilding a Startup Stack with AngularJS
Building a Startup Stack with AngularJS
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developers
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJS
 
"Angular.js Concepts in Depth" by Aleksandar Simović
"Angular.js Concepts in Depth" by Aleksandar Simović"Angular.js Concepts in Depth" by Aleksandar Simović
"Angular.js Concepts in Depth" by Aleksandar Simović
 
The AngularJS way
The AngularJS wayThe AngularJS way
The AngularJS way
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
 
Overview of Node JS
Overview of Node JSOverview of Node JS
Overview of Node JS
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
Angular js
Angular jsAngular js
Angular js
 
Workshop 17: EmberJS parte II
Workshop 17: EmberJS parte IIWorkshop 17: EmberJS parte II
Workshop 17: EmberJS parte II
 
Workshop 19: ReactJS Introduction
Workshop 19: ReactJS IntroductionWorkshop 19: ReactJS Introduction
Workshop 19: ReactJS Introduction
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web Application
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 

Destaque

Mappeoppgave 2 2003
Mappeoppgave 2   2003Mappeoppgave 2   2003
Mappeoppgave 2 2003
Anniken
 
Enjoy Thinking
Enjoy ThinkingEnjoy Thinking
Enjoy Thinking
fuseto
 

Destaque (20)

ngMess: AngularJS Dependency Injection
ngMess: AngularJS Dependency InjectionngMess: AngularJS Dependency Injection
ngMess: AngularJS Dependency Injection
 
AngularJS - dependency injection
AngularJS - dependency injectionAngularJS - dependency injection
AngularJS - dependency injection
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
AngularJS intro
AngularJS introAngularJS intro
AngularJS intro
 
Getting merged
Getting mergedGetting merged
Getting merged
 
Modules and injector
Modules and injectorModules and injector
Modules and injector
 
Gettings started with the superheroic JavaScript library AngularJS
Gettings started with the superheroic JavaScript library AngularJSGettings started with the superheroic JavaScript library AngularJS
Gettings started with the superheroic JavaScript library AngularJS
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)
 
Primerafase
PrimerafasePrimerafase
Primerafase
 
Mappeoppgave 2 2003
Mappeoppgave 2   2003Mappeoppgave 2   2003
Mappeoppgave 2 2003
 
100c
100c100c
100c
 
Dojotoolkit Nedir?
Dojotoolkit Nedir?Dojotoolkit Nedir?
Dojotoolkit Nedir?
 
The Ants
The AntsThe Ants
The Ants
 
Enjoy Thinking
Enjoy ThinkingEnjoy Thinking
Enjoy Thinking
 
100a
100a100a
100a
 
Introduction to Elgg
Introduction to ElggIntroduction to Elgg
Introduction to Elgg
 
Aegee kyiv. презентація загальна
Aegee kyiv. презентація загальнаAegee kyiv. презентація загальна
Aegee kyiv. презентація загальна
 
Sociale medier: Værktøjer og kategorier
Sociale medier: Værktøjer og kategorierSociale medier: Værktøjer og kategorier
Sociale medier: Værktøjer og kategorier
 

Semelhante a Dependency Injection @ AngularJS

OpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and Mobile
OpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and MobileOpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and Mobile
OpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and Mobile
Dierk König
 

Semelhante a Dependency Injection @ AngularJS (20)

Explaination of angular
Explaination of angularExplaination of angular
Explaination of angular
 
Integrating Angular js & three.js
Integrating Angular js & three.jsIntegrating Angular js & three.js
Integrating Angular js & three.js
 
AngularJs Crash Course
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash Course
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
 
Backbone
BackboneBackbone
Backbone
 
An approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSocketsAn approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSockets
 
Mean stack Magics
Mean stack MagicsMean stack Magics
Mean stack Magics
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
 
Opinionated AngularJS
Opinionated AngularJSOpinionated AngularJS
Opinionated AngularJS
 
Webinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST APIWebinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST API
 
Webinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST APIWebinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST API
 
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analystsMeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
 
Introduction to Backbone.js & Marionette.js
Introduction to Backbone.js & Marionette.jsIntroduction to Backbone.js & Marionette.js
Introduction to Backbone.js & Marionette.js
 
AngularJS $Provide Service
AngularJS $Provide ServiceAngularJS $Provide Service
AngularJS $Provide Service
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS Basics
 
NestJS
NestJSNestJS
NestJS
 
OpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and Mobile
OpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and MobileOpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and Mobile
OpenDolphin: Enterprise Apps for collaboration on Desktop, Web, and Mobile
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript
 
Angular module
Angular moduleAngular module
Angular module
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Dependency Injection @ AngularJS

  • 1. Dependency Injection @ AngularJS Ran Mizrahi (@ranm8) Open Source Dpt. Leader @ CodeOasis Monday, September 9, 13
  • 2. About CodeOasis • CodeOasis specializes in cutting-edge web solutions. • Large variety of customers (from startups to enterprises). • We LOVE JavaScript (-: • Technologies we love: • Symfony2 • AngularJS • nodeJS • HTML5 • CSS3 • Our Microsoft department works with C#, WPF, etc. Monday, September 9, 13
  • 4. The Problem function SessionStore() {} SessionStore.prototype = { set: function(name, value) { window.localStorage.setItem(name, value); }, get: function(name) { return window.localStorage.getItem(name); } } function User() { this.sessionStore = new SessionStore(); } User.prototype = { setSession: function(session) { this.sessionStore.set('session', session); }, getSession: function() { return this.sessionStore.get('session'); } } Monday, September 9, 13
  • 5. The Problem Everything goes well and the code is working. But now we have to change the session name... We can use a global variable: sessionName = 'newSessionName'; function User() { this.sessionStore = new SessionStore(); } // ... Maybe we should hard-coded pass it to the store: function User() { this.sessionStore = new SessionStore('newSessionName'); } // ... Monday, September 9, 13
  • 6. The Problem How would you change the entire SessionStore implementation? Cookies Server ... function User() { this.sessionStore = registry.get('SessionStore'); } // ... Should we use some global registry object?? How would we test the User?? Monday, September 9, 13
  • 7. The Problem All those solutions are bad because: • Couples code to one implementation. • Hard to configure • Cannot change the implementation without changing the User prototype. • Untestable code unless you monkey patch it. Monday, September 9, 13
  • 8. Dependency Injection Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them. -- Wikipedia Monday, September 9, 13
  • 9. Dependency Injection To The Rescue! Instead of instantiating the SessionStore within the User... function User(sessionStore) { this.sessionStore = sessionStore; } // ... var user = new User(new SessionStore()); JUST INJECT IT!!! Monday, September 9, 13
  • 10. Advantages Of Using DI Use different session store strategies... function User(sessionStore) { this.sessionStore = sessionStore; } // ... var user = new User(new CookieSessionStore()); Monday, September 9, 13
  • 11. Advantages Of Using DI Configuration becomes easy... function User(sessionStore) { this.sessionStore = sessionStore; } // ... var user = new User(new SessionStore('mySessionName')); Monday, September 9, 13
  • 12. Advantages Of Using DI Now we can easily mock the SessionStore (for testing purposes)... function User(sessionStore) { this.sessionStore = sessionStore; } // ... var user = new User(new MockSessionStore()); Monday, September 9, 13
  • 13. All those things makes our code MAINTAINABLE because we’ve.. Less code Extensible Testable Monday, September 9, 13
  • 14. But How To Scale It?!!?!? But what if we have a slightly more complex application.. And we do that in many different places around our application: var user = new User(new SessionStore(new SomeThirdParty(jQuery), new Http(new Thing())), new Something()); //.... var user = new User(new SessionStore(new SomeThirdParty(jQuery), new Http(new Thing())), new Something()); //.... var user = new User(new SessionStore(new SomeThirdParty(jQuery), new Http(new Thing())), new Something()); Monday, September 9, 13
  • 16. DI Container To The Rescue Monday, September 9, 13
  • 17. DI Container (e.g. Injector, Provider) • Instantiates objects and their dependencies on demand. • Allows to configure objects before instantiation. • Can instantiate new objects on demand or provide existing ones from cache. • The objects must never know they are being managed by the container. • A container should be able to manage any object. Monday, September 9, 13
  • 19. How The DI Injector Works?! • Angular inject the requested service by the function argument names. • Can also be done with an array. • Once requested Angular’s injector would instantiate the requested service and inject it. angular.module('myModule') .controller('MyCtrl', MyCtrl); function MyCtrl($http) { $http.get('http://google.com').then(getTheMonkey); } Monday, September 9, 13
  • 20. The Array Notation • Allows minifiers to preserve argument names for the dependency injection to work with. • More flexible - Separates dependency declaration from your unit. angular.module('myModule') .controller('MyCtrl', ['$http', MyCtrl]); function MyCtrl($http) { $http.get('http://google.com').then(getTheMonkey); } Monday, September 9, 13
  • 21. Changing The Implementation angular.module('myModule') .controller('MyCtrl', ['myHttp', MyCtrl]) .factory('myHttp', ['$q', myHttp]); function myHttp($q) { return { get: function() { var defer = $q.defer(); // Do something with XHR and return a promise... return defer.promise; } }; } function MyCtrl($http) { $http.get('http://google.com').then(someCallback); } • Changes the implementation by changing only the array notation. • Angular’s injector instantiates the dependencies of each dependency. Monday, September 9, 13
  • 22. How Do I Use It? Monday, September 9, 13
  • 23. Service/Factory A service is the Angular way of exposing objects within the $injector. • Can have multiple dependencies that will be injected when invoked. angular.module('myModule') .service('myHttp', ['$q', myHttp]); function myHttp($q) { this.get = function() { var defer = $q.defer(); // Do something with XHR and return a promise... return defer.promise; }; } Monday, September 9, 13
  • 24. Factory Shorthand for registering services without a constructor function (assigned to $get property directly). angular.module('myModule') .factory('myHttp', ['$q', myHttp]); function myHttp($q) { return { get: function() { var defer = $q.defer(); // Do something with XHR and return a promise... return defer.promise; } }; } Monday, September 9, 13
  • 25. Provider Registers a provider to a service. • Allows the save configuration state to the service. • Only constants can be injected. • The provider is a constructor function. • $get is a function that returns the actual service. Monday, September 9, 13
  • 26. Provider angular.module('myModule') .provider('myHttp', myHttp); function myHttp() { var baseUrl; this.baseUrl = function(value) { if (!value) { return baseUrl; } baseUrl = value; }; this.$get = ['$q', function() { // myHttp service implementation... }]; } Monday, September 9, 13
  • 27. Configuration Phase vs. Run Phase Configuration Phase Run Phase • Runs before any service was instantiated. • Only providers can be injected. • Each provider is injected with the “Provider” suffix (e.g. $locationProvider) • Allows to purely configure the services state. • Services state should be not be changed now (already configured during run phase). • Providers now cannot be injected. Monday, September 9, 13
  • 28. Config Use the service providers to configure the services state during the config phase to the run phase. angular.module('myModule') .config(['myHttpProvider', '$locationProvider', appConfig]); function appConfig(myHttpProvider, $locationProvider) { // Configure app to use HTML5 History API.. $locationProvider.html5Mode(true); // Configure my service baseUrl.. myHttpProvider.baseUrl('http://www.example.com'); } Monday, September 9, 13
  • 29. Value Value is a shorthand to register a simple value as a service. angular.module('myModule') .value('myHttp', 'some string'); Monday, September 9, 13
  • 30. Constant Constant is the same as value, but unlike value it can be injected to configuration function angular.module('myModule') .constant('someConstant', '123'); Monday, September 9, 13
  • 31. Angular’s DI In Testing describe('myHttp', function() { var mockQ = { then: function(){} }, http; beforeEach(module(function($provide) { $provide.value('$q', mockQ); })); beforeEach(inject(function(myHttp) { http = myHttp; })); describe('#get()', function() { it('should return a promise', function() { // test your code here }); }); }); Monday, September 9, 13