SlideShare a Scribd company logo
1 of 31
Dependency Injection
Faiz Mohamed Haneef
Agenda
• Dependency Injection - Design Pattern
• Dependency Injection/DI - Framework
• Create DI Framework with custom compiler like Angular (Hands-On)
• Angular 2+ DI Framework
Before We Start
• Stop Me if Something Isn’t clear.
• Raise your hands / Dance / Wave/ Clap - Grab my attention
• Ground Rules are set.. Lets Start!!!
Design Patterns
• What is it?
Different Patterns
var myCode = {
name: 'Faiz',
sayName: function(){
console.log(this.name);
}
}
myCode.sayName();
var name = "Faiz";
function sayName(name) {
console.log(name);
}
sayName(name);
Design Patterns
• A general reusable solution to a commonly occurring problem
• Are formalized best practices
• Obtained by trial and error
1 Creational Patterns
These design patterns provide a way to create objects while hiding
the creation logic, rather than instantiating objects directly using
new operator. This gives program more flexibility in deciding which
objects need to be created for a given use case.
2 Structural Patterns
These design patterns concern class and object composition. Concept
of inheritance is used to compose interfaces and define ways to
compose objects to obtain new functionalities.
3 Behavioral Patterns
These design patterns are specifically concerned with
communication between objects.
Design Principles
• Law Of Demeter
• Single Responsibility Principle
• Inversion Of Control
Class in Javascript vs Typescript
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");
var Greeter = function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
var greeter = new Greeter("world");
Quick Recap
• So far good?
• We understand
• Design Patterns
• Design Principles
• TS Class
Lets JUMP into DI !!!!
What's the problem?
export class Car {
public engine: Engine;
public tires: Tires;
public description = 'No DI';
constructor() {
this.engine = new Engine();
this.tires = new Tires();
}
}
What if the Engine class evolves and its
constructor requires a parameter?
What if you want to put a different
brand of tires on your Car?
You have no control over the car's hidden
dependencies. When you can't control the
dependencies, a class becomes difficult to
test.
DI in Javascript vs Typescript
With DI - TS
class Car {
public engine: Engine;
public tires: Tires;
public description = ’With DI';
constructor(engine: Engine, tires: Tires) {
this.engine = engine;
this.tires = tires;
}
}
WITHOUT DI - JS
function Car() {
this.description = 'No DI';
this.engine = new Engine();
this.tires = new Tires();
}
WITH DI - JS
function Car(engine, tires) {
this.description = ’With DI';
this.engine = engine;
this.tires = tires;
}
let car = new Car(new Engine(), new Tires());
Dependency Injection Pattern (Theory)
• The core concept of DI is to invert the control of managing
dependencies so that instead of the client having to manage its own
dependencies, you instead delegate this responsibility to the code
which actually calls your client, typically passing in dependencies as
arguments to that client.
• This is where the name “dependency injection” comes from –
you inject the dependencies into your client code during the
execution of that code.
Inversion Of Control Design Principle
• In object-oriented programming, there are several basic techniques to
implement inversion of control. These are:
• Using a service locator pattern
• Using dependency injection, for example
• Constructor injection
• Parameter injection
• Setter injection
• Interface injection
• Using a contextualized lookup
• Using template method design pattern
• Using strategy design pattern
Benefits of DI
• Loose coupling.
• Testing is very simple.
class MockEngine extends Engine { cylinders = 8; }
class MockTires extends Tires { make = 'YokoGoodStone'; }
// Test car with 8 cylinders and YokoGoodStone tires.
let car = new Car(new MockEngine(), new MockTires());
Detriments of DI
• More difficult to trace.
Consumer Issue
• The consumer of Car has the problem. The consumer must update the car
creation code to something like this:
class Engine2 {
constructor(public cylinders: number) { }
}
// Super car with 12 cylinders and Flintstone tires.
let bigCylinders = 12;
let car = new Car(new Engine2(bigCylinders), new Tires());
How about let car = injector.get(Car);
• The Car knows nothing about creating an Engine or Tires.
• The consumer knows nothing about creating a Car
• This is what a dependency injection framework is all about.
Quick Hands On
• Demo to create an injection Framework like Angular 1
• Demo on Custom Template Compiler as well.
Angular 2 DI
• @NgModule, @Component
Metadata: Providers - A service provider provides the concrete, runtime
version of a dependency value.
@Injectable - decorator identifies a service class that might require
injected dependencies.
injector.get(Car) in Angular 2+ : Injector
• Who?
Angular injector is responsible for creating service instances and injecting
them. The injector maintains an internal token-provider map that it
references when asked for a dependency.
• How?
Register providers with an injector before the injector can create that
service. Angular decorators - @Component and @NgModule accept
metadata with a providers property.
Inject a dependency in the component's constructor by specifying
a constructor parameter with the dependency type
Service Scope
• @NgModule or @Component?
Angular 2+ DI - Characteristics
• Singleton services
• Hierarchical injection system – i.e. if @Component.providers exists, it
also creates a new child injector
The provide object literal
• Responsibility
Locating a dependency value and registering the provider
• Syntax
providers: [Logger] same as
[{ provide: Logger, useClass: Logger }]
Alternative class providers
• [{ provide: Logger, useClass: BetterLogger }]
Class provider with dependencies
@Injectable()
export class EvenBetterLogger extends Logger {
constructor(private userService: UserService) { super(); }
log(message: string) {
let name = this.userService.user.name;
super.log(`Message to ${name}: ${message}`);
}
}
Aliased class providers
[ NewLogger,
// Not aliased! Creates two instances of `NewLogger`
{ provide: OldLogger, useClass: NewLogger}]
The solution: alias with the useExisting option.
[ NewLogger,
// Alias OldLogger w/ reference to NewLogger
{ provide: OldLogger, useExisting: NewLogger}]
Value providers
• // An object in the shape of the logger service
• export function SilentLoggerFn() {}
• const silentLogger = {
• logs: ['Silent logger says "Shhhhh!". Provided via "useValue"'],
• log: SilentLoggerFn
• };
• Then you register a provider with the useValue option, which makes this
object play the logger role.
• [{ provide: Logger, useValue: silentLogger }]
Non-class dependencies
• InjectionToken
Factory providers
src/app/heroes/hero.service.ts
constructor(
private logger: Logger,
private isAuthorized: boolean) { }
)
export let heroServiceProvider = {
provide: HeroService,
useFactory: heroServiceFactory,
deps: [Logger, UserService]
};
src/app/heroes/hero.service.provider.ts (excerpt)
let heroServiceFactory = (logger: Logger, userService: UserService) => {
return new HeroService(logger, userService.user.isAuthorized);
};
The useFactory field tells Angular
that the provider is a factory
function.
The deps property is an array
of provider tokens.
THANK YOU!

More Related Content

What's hot

Angular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersAngular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersOswald Campesato
 
Angular 2: core concepts
Angular 2: core conceptsAngular 2: core concepts
Angular 2: core conceptsCodemotion
 
Tech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new frameworkTech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new frameworkCodemotion
 
Angular 2: What's New?
Angular 2: What's New?Angular 2: What's New?
Angular 2: What's New?jbandi
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type scriptRavi Mone
 
Angular 2 - Core Concepts
Angular 2 - Core ConceptsAngular 2 - Core Concepts
Angular 2 - Core ConceptsFabio Biondi
 
Angular interview questions
Angular interview questionsAngular interview questions
Angular interview questionsGoa App
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice PresentationDmitry Buzdin
 
Angular Application Testing
Angular Application TestingAngular Application Testing
Angular Application TestingTroy Miles
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS ComponentsSurendra kumar
 
Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"
Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"
Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"Fwdays
 
The evolution of Angular 2 @ AngularJS Munich Meetup #5
The evolution of Angular 2 @ AngularJS Munich Meetup #5The evolution of Angular 2 @ AngularJS Munich Meetup #5
The evolution of Angular 2 @ AngularJS Munich Meetup #5Johannes Weber
 
Angular 2... so can I use it now??
Angular 2... so can I use it now??Angular 2... so can I use it now??
Angular 2... so can I use it now??Laurent Duveau
 
An introduction to Angular2
An introduction to Angular2 An introduction to Angular2
An introduction to Angular2 Apptension
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2Naveen Pete
 
AngularConf2016 - A leap of faith !?
AngularConf2016 - A leap of faith !?AngularConf2016 - A leap of faith !?
AngularConf2016 - A leap of faith !?Alessandro Giorgetti
 
Angular 2 overview
Angular 2 overviewAngular 2 overview
Angular 2 overviewJesse Warden
 
Creating custom Validators on Reactive Forms using Angular 6
Creating custom Validators on Reactive Forms using Angular 6Creating custom Validators on Reactive Forms using Angular 6
Creating custom Validators on Reactive Forms using Angular 6AIMDek Technologies
 

What's hot (20)

Angular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersAngular1x and Angular 2 for Beginners
Angular1x and Angular 2 for Beginners
 
Angular 2: core concepts
Angular 2: core conceptsAngular 2: core concepts
Angular 2: core concepts
 
Tech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new frameworkTech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new framework
 
Angular 2: What's New?
Angular 2: What's New?Angular 2: What's New?
Angular 2: What's New?
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type script
 
Angular 2 - Core Concepts
Angular 2 - Core ConceptsAngular 2 - Core Concepts
Angular 2 - Core Concepts
 
Angular interview questions
Angular interview questionsAngular interview questions
Angular interview questions
 
Angular 5
Angular 5Angular 5
Angular 5
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice Presentation
 
Angular Application Testing
Angular Application TestingAngular Application Testing
Angular Application Testing
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components
 
Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"
Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"
Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"
 
The evolution of Angular 2 @ AngularJS Munich Meetup #5
The evolution of Angular 2 @ AngularJS Munich Meetup #5The evolution of Angular 2 @ AngularJS Munich Meetup #5
The evolution of Angular 2 @ AngularJS Munich Meetup #5
 
Angular 2... so can I use it now??
Angular 2... so can I use it now??Angular 2... so can I use it now??
Angular 2... so can I use it now??
 
An introduction to Angular2
An introduction to Angular2 An introduction to Angular2
An introduction to Angular2
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
AngularConf2016 - A leap of faith !?
AngularConf2016 - A leap of faith !?AngularConf2016 - A leap of faith !?
AngularConf2016 - A leap of faith !?
 
Angular 2 overview
Angular 2 overviewAngular 2 overview
Angular 2 overview
 
Creating custom Validators on Reactive Forms using Angular 6
Creating custom Validators on Reactive Forms using Angular 6Creating custom Validators on Reactive Forms using Angular 6
Creating custom Validators on Reactive Forms using Angular 6
 

Similar to Neoito — Design patterns and depenedency injection

Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.jsIvano Malavolta
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsWebStackAcademy
 
Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?GlobalLogic Ukraine
 
The Basics Angular JS
The Basics Angular JS The Basics Angular JS
The Basics Angular JS OrisysIndia
 
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in ScalaDsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in ScalaUgo Matrangolo
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Doris Chen
 
Angularjs2 presentation
Angularjs2 presentationAngularjs2 presentation
Angularjs2 presentationdharisk
 
Angularjs for kolkata drupal meetup
Angularjs for kolkata drupal meetupAngularjs for kolkata drupal meetup
Angularjs for kolkata drupal meetupGoutam Dey
 
The State of Front-end At CrowdTwist
The State of Front-end At CrowdTwistThe State of Front-end At CrowdTwist
The State of Front-end At CrowdTwistMark Fayngersh
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014Ran Wahle
 
ME vs WEB - AngularJS Fundamentals
ME vs WEB - AngularJS FundamentalsME vs WEB - AngularJS Fundamentals
ME vs WEB - AngularJS FundamentalsAviran Cohen
 
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docxBroncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docxcurwenmichaela
 
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docxBroncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docxhartrobert670
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs WorkshopRan Wahle
 

Similar to Neoito — Design patterns and depenedency injection (20)

Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.js
 
Lec18
Lec18Lec18
Lec18
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
 
Handlebars & Require JS
Handlebars  & Require JSHandlebars  & Require JS
Handlebars & Require JS
 
mean stack
mean stackmean stack
mean stack
 
Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?
 
SDWest2005Goetsch
SDWest2005GoetschSDWest2005Goetsch
SDWest2005Goetsch
 
The Basics Angular JS
The Basics Angular JS The Basics Angular JS
The Basics Angular JS
 
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in ScalaDsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
 
Angularjs2 presentation
Angularjs2 presentationAngularjs2 presentation
Angularjs2 presentation
 
Angularjs for kolkata drupal meetup
Angularjs for kolkata drupal meetupAngularjs for kolkata drupal meetup
Angularjs for kolkata drupal meetup
 
The State of Front-end At CrowdTwist
The State of Front-end At CrowdTwistThe State of Front-end At CrowdTwist
The State of Front-end At CrowdTwist
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
ME vs WEB - AngularJS Fundamentals
ME vs WEB - AngularJS FundamentalsME vs WEB - AngularJS Fundamentals
ME vs WEB - AngularJS Fundamentals
 
Foundations of programming
Foundations of programmingFoundations of programming
Foundations of programming
 
Angular 9
Angular 9 Angular 9
Angular 9
 
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docxBroncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
 
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docxBroncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
Broncosbuild.xmlBuilds, tests, and runs the project Broncos..docx
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
 

More from Neoito

Neoito — NativeScript Best Coding Practices
Neoito — NativeScript Best Coding PracticesNeoito — NativeScript Best Coding Practices
Neoito — NativeScript Best Coding PracticesNeoito
 
Neoito — *NIX kungfu for web devs
Neoito — *NIX kungfu for web devsNeoito — *NIX kungfu for web devs
Neoito — *NIX kungfu for web devsNeoito
 
Neoito — Secure coding practices
Neoito — Secure coding practicesNeoito — Secure coding practices
Neoito — Secure coding practicesNeoito
 
Neoito — How modern browsers work
Neoito — How modern browsers workNeoito — How modern browsers work
Neoito — How modern browsers workNeoito
 
Neoito — React 101
Neoito — React 101Neoito — React 101
Neoito — React 101Neoito
 
Neoito — Scaling node.js
Neoito — Scaling node.jsNeoito — Scaling node.js
Neoito — Scaling node.jsNeoito
 
Neoito — Grid layout
Neoito — Grid layoutNeoito — Grid layout
Neoito — Grid layoutNeoito
 
Neoito — Software licensing
Neoito — Software licensingNeoito — Software licensing
Neoito — Software licensingNeoito
 
Neoito — GitLab for project management
Neoito — GitLab for project managementNeoito — GitLab for project management
Neoito — GitLab for project managementNeoito
 
Neoito — Routing and navigation in Angular
Neoito — Routing and navigation in AngularNeoito — Routing and navigation in Angular
Neoito — Routing and navigation in AngularNeoito
 
Neoito — Animations in Angular 5
Neoito — Animations in Angular 5Neoito — Animations in Angular 5
Neoito — Animations in Angular 5Neoito
 
Neoito — A roadmap to Angular
Neoito — A roadmap to AngularNeoito — A roadmap to Angular
Neoito — A roadmap to AngularNeoito
 
Neoito — Intro to WebSockets
Neoito — Intro to WebSocketsNeoito — Intro to WebSockets
Neoito — Intro to WebSocketsNeoito
 
Neoito — Typography for the web
Neoito — Typography for the webNeoito — Typography for the web
Neoito — Typography for the webNeoito
 

More from Neoito (14)

Neoito — NativeScript Best Coding Practices
Neoito — NativeScript Best Coding PracticesNeoito — NativeScript Best Coding Practices
Neoito — NativeScript Best Coding Practices
 
Neoito — *NIX kungfu for web devs
Neoito — *NIX kungfu for web devsNeoito — *NIX kungfu for web devs
Neoito — *NIX kungfu for web devs
 
Neoito — Secure coding practices
Neoito — Secure coding practicesNeoito — Secure coding practices
Neoito — Secure coding practices
 
Neoito — How modern browsers work
Neoito — How modern browsers workNeoito — How modern browsers work
Neoito — How modern browsers work
 
Neoito — React 101
Neoito — React 101Neoito — React 101
Neoito — React 101
 
Neoito — Scaling node.js
Neoito — Scaling node.jsNeoito — Scaling node.js
Neoito — Scaling node.js
 
Neoito — Grid layout
Neoito — Grid layoutNeoito — Grid layout
Neoito — Grid layout
 
Neoito — Software licensing
Neoito — Software licensingNeoito — Software licensing
Neoito — Software licensing
 
Neoito — GitLab for project management
Neoito — GitLab for project managementNeoito — GitLab for project management
Neoito — GitLab for project management
 
Neoito — Routing and navigation in Angular
Neoito — Routing and navigation in AngularNeoito — Routing and navigation in Angular
Neoito — Routing and navigation in Angular
 
Neoito — Animations in Angular 5
Neoito — Animations in Angular 5Neoito — Animations in Angular 5
Neoito — Animations in Angular 5
 
Neoito — A roadmap to Angular
Neoito — A roadmap to AngularNeoito — A roadmap to Angular
Neoito — A roadmap to Angular
 
Neoito — Intro to WebSockets
Neoito — Intro to WebSocketsNeoito — Intro to WebSockets
Neoito — Intro to WebSockets
 
Neoito — Typography for the web
Neoito — Typography for the webNeoito — Typography for the web
Neoito — Typography for the web
 

Recently uploaded

Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 

Recently uploaded (20)

Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

Neoito — Design patterns and depenedency injection

  • 2. Agenda • Dependency Injection - Design Pattern • Dependency Injection/DI - Framework • Create DI Framework with custom compiler like Angular (Hands-On) • Angular 2+ DI Framework
  • 3. Before We Start • Stop Me if Something Isn’t clear. • Raise your hands / Dance / Wave/ Clap - Grab my attention • Ground Rules are set.. Lets Start!!!
  • 5. Different Patterns var myCode = { name: 'Faiz', sayName: function(){ console.log(this.name); } } myCode.sayName(); var name = "Faiz"; function sayName(name) { console.log(name); } sayName(name);
  • 6. Design Patterns • A general reusable solution to a commonly occurring problem • Are formalized best practices • Obtained by trial and error
  • 7. 1 Creational Patterns These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. 2 Structural Patterns These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. 3 Behavioral Patterns These design patterns are specifically concerned with communication between objects.
  • 8. Design Principles • Law Of Demeter • Single Responsibility Principle • Inversion Of Control
  • 9. Class in Javascript vs Typescript class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } let greeter = new Greeter("world"); var Greeter = function Greeter(message) { this.greeting = message; } Greeter.prototype.greet = function () { return "Hello, " + this.greeting; }; var greeter = new Greeter("world");
  • 10. Quick Recap • So far good? • We understand • Design Patterns • Design Principles • TS Class Lets JUMP into DI !!!!
  • 11. What's the problem? export class Car { public engine: Engine; public tires: Tires; public description = 'No DI'; constructor() { this.engine = new Engine(); this.tires = new Tires(); } } What if the Engine class evolves and its constructor requires a parameter? What if you want to put a different brand of tires on your Car? You have no control over the car's hidden dependencies. When you can't control the dependencies, a class becomes difficult to test.
  • 12. DI in Javascript vs Typescript With DI - TS class Car { public engine: Engine; public tires: Tires; public description = ’With DI'; constructor(engine: Engine, tires: Tires) { this.engine = engine; this.tires = tires; } } WITHOUT DI - JS function Car() { this.description = 'No DI'; this.engine = new Engine(); this.tires = new Tires(); } WITH DI - JS function Car(engine, tires) { this.description = ’With DI'; this.engine = engine; this.tires = tires; } let car = new Car(new Engine(), new Tires());
  • 13. Dependency Injection Pattern (Theory) • The core concept of DI is to invert the control of managing dependencies so that instead of the client having to manage its own dependencies, you instead delegate this responsibility to the code which actually calls your client, typically passing in dependencies as arguments to that client. • This is where the name “dependency injection” comes from – you inject the dependencies into your client code during the execution of that code.
  • 14. Inversion Of Control Design Principle • In object-oriented programming, there are several basic techniques to implement inversion of control. These are: • Using a service locator pattern • Using dependency injection, for example • Constructor injection • Parameter injection • Setter injection • Interface injection • Using a contextualized lookup • Using template method design pattern • Using strategy design pattern
  • 15. Benefits of DI • Loose coupling. • Testing is very simple. class MockEngine extends Engine { cylinders = 8; } class MockTires extends Tires { make = 'YokoGoodStone'; } // Test car with 8 cylinders and YokoGoodStone tires. let car = new Car(new MockEngine(), new MockTires());
  • 16. Detriments of DI • More difficult to trace.
  • 17. Consumer Issue • The consumer of Car has the problem. The consumer must update the car creation code to something like this: class Engine2 { constructor(public cylinders: number) { } } // Super car with 12 cylinders and Flintstone tires. let bigCylinders = 12; let car = new Car(new Engine2(bigCylinders), new Tires());
  • 18. How about let car = injector.get(Car); • The Car knows nothing about creating an Engine or Tires. • The consumer knows nothing about creating a Car • This is what a dependency injection framework is all about.
  • 19. Quick Hands On • Demo to create an injection Framework like Angular 1 • Demo on Custom Template Compiler as well.
  • 20. Angular 2 DI • @NgModule, @Component Metadata: Providers - A service provider provides the concrete, runtime version of a dependency value. @Injectable - decorator identifies a service class that might require injected dependencies.
  • 21. injector.get(Car) in Angular 2+ : Injector • Who? Angular injector is responsible for creating service instances and injecting them. The injector maintains an internal token-provider map that it references when asked for a dependency. • How? Register providers with an injector before the injector can create that service. Angular decorators - @Component and @NgModule accept metadata with a providers property. Inject a dependency in the component's constructor by specifying a constructor parameter with the dependency type
  • 22. Service Scope • @NgModule or @Component?
  • 23. Angular 2+ DI - Characteristics • Singleton services • Hierarchical injection system – i.e. if @Component.providers exists, it also creates a new child injector
  • 24. The provide object literal • Responsibility Locating a dependency value and registering the provider • Syntax providers: [Logger] same as [{ provide: Logger, useClass: Logger }]
  • 25. Alternative class providers • [{ provide: Logger, useClass: BetterLogger }]
  • 26. Class provider with dependencies @Injectable() export class EvenBetterLogger extends Logger { constructor(private userService: UserService) { super(); } log(message: string) { let name = this.userService.user.name; super.log(`Message to ${name}: ${message}`); } }
  • 27. Aliased class providers [ NewLogger, // Not aliased! Creates two instances of `NewLogger` { provide: OldLogger, useClass: NewLogger}] The solution: alias with the useExisting option. [ NewLogger, // Alias OldLogger w/ reference to NewLogger { provide: OldLogger, useExisting: NewLogger}]
  • 28. Value providers • // An object in the shape of the logger service • export function SilentLoggerFn() {} • const silentLogger = { • logs: ['Silent logger says "Shhhhh!". Provided via "useValue"'], • log: SilentLoggerFn • }; • Then you register a provider with the useValue option, which makes this object play the logger role. • [{ provide: Logger, useValue: silentLogger }]
  • 30. Factory providers src/app/heroes/hero.service.ts constructor( private logger: Logger, private isAuthorized: boolean) { } ) export let heroServiceProvider = { provide: HeroService, useFactory: heroServiceFactory, deps: [Logger, UserService] }; src/app/heroes/hero.service.provider.ts (excerpt) let heroServiceFactory = (logger: Logger, userService: UserService) => { return new HeroService(logger, userService.user.isAuthorized); }; The useFactory field tells Angular that the provider is a factory function. The deps property is an array of provider tokens.

Editor's Notes

  1. https://en.wikipedia.org/wiki/Inversion_of_control
  2. The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs. In its general form, the LoD is a specific case of loose coupling. The guideline was proposed by Ian Holland at Northeastern University towards the end of 1987, and can be succinctly summarized in each of the following ways:[1] Each unit should have only limited knowledge about other units: only units "closely" related to the current unit. Each unit should only talk to its friends; don't talk to strangers. Only talk to your immediate friends. https://en.wikipedia.org/wiki/Law_of_Demeter https://en.wikipedia.org/wiki/Single_responsibility_principle The single responsibility principle is a computer programming principle that states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility. Robert C. Martinexpresses the principle as, "A class should have only one reason to change."[1]
  3. https://www.typescriptlang.org/play/
  4.  Instead of asking for them, the Car constructor instantiates its own copies from the very specific classes Engine and Tires. Forcing me to know how to create Engine class and this is tightly coupled
  5. https://www.typescriptlang.org/play/
  6. https://thesocietea.org/2017/03/design-patterns-dependency-injection/
  7. https://en.wikipedia.org/wiki/Inversion_of_control
  8. With DI, your code is by default more loosely coupled which makes it easier to “plug-and-play” throughout your application; for example, you don’t have to worry about using a dependency that was potentially declared in an external scope compared to where you’re actually using it.  https://en.wikipedia.org/wiki/Dependency_injection#Three_types_of_dependency_injection
  9. When you’re debugging code that’s using DI, if the error stems from a dependency, then you may need to follow your stack trace a little bit further to see where the error actually occurs. Because dependencies no longer exist in the same file and/or class as where your logic is happening, you need to know exactly what called the code in question to understand where the problem may lie. https://www.journaldev.com/1827/java-design-patterns-example-tutorial https://sourcemaking.com/design_patterns https://gist.github.com/demisx/9605099 https://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html#dependency-injection-as-a-pattern Vojta Jina gave a great talk on dependency injection at ng-conf 2014 https://docs.angularjs.org/api/auto/service/$injector#annotate
  10. To be precise, Angular module providers are registered with the root injector unless the module is lazy loaded. In this sample, all modules are eagerly loaded when the application starts, so all module providers are registered with the app's root injector.