SlideShare a Scribd company logo
Dependency Injection
Decoupling dependencies for flexible app design
doug.ayers@salesforce.com, @douglascayers
Doug Ayers, Technical Curriculum Developer, Trailhead
Doug Ayers
Technical Curriculum
Developer, Trailhead
@douglascayers
github.com/douglascayers
douglascayers.com
Developer, Educator, Blogger
“The fun way to
learn Salesforce”
Exploring Use Cases for Dependency Injection
https://www.meetup.com/ForceDotCom/events/253817247/
Look for recording to be posted to the Bay Area Salesforce Dev Group YouTube Channel
Learn directly from Salesforce experts at #DF18 Bootcamp
https://www.salesforce.com/dreamforce/certification/
Pre-Conference
Bootcamp:
Developing Applications
using Salesforce DX
and Heroku Pipelines
• 3 Days
• Instructor-Led
• Hands-On
• I’ll be there 😎
This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the
assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we
make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or service availability, subscriber
growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any
statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services.
The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new
products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in
our Web hosting, breach of our security measures, the outcome of any litigation, risks associated with completed and any possible mergers and acquisitions, the
immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new
releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise
customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-K for the
most recent fiscal year and in our quarterly report on Form 10-Q for the most recent fiscal quarter. These documents and others containing important disclosures are
available on the SEC Filings section of the Investor Information section of our Web site.
Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be
delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available.
Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
Statement under the Private Securities Litigation Reform Act of 1995
Forward-Looking Statement
Agenda
• What is dependency injection and what does it solve?
• Walkthrough: refactoring tightly coupled code
• Overview of force-di open source project
• Demo force-di with Lightning, Visualforce, Apex, and Flows
• Resources
• Q&A
What does Dependency Injection solve?
What does Dependency Injection solve?
Tight coupling of
which message
class to use.
Introduce an interface
so the concrete
implementations can be
swapped out.
Move logic of which
implementation to use,
which decouples the
greetings method from the
message provider.
Move logic of which
implementation to use,
which decouples the
greetings method from the
message provider.
We can take this further by
injecting the implementation
to use at runtime,
completely decoupling the
classes.
Now we’ve completely
decoupled the ChatApp
from the implementation
dependencies by looking up
at runtime what to use.
Two flavors of constructor
injection by either passing in
the class to use or looking it
up in real-time.
Design patterns for decoupling dependencies
Dependency Inversion and Injection
An app codes to interfaces so that
behavior can be swapped out with little
to no code changes to the app.
Design patterns for decoupling dependencies
Dependency Inversion and Injection
Implementations can be swapped out
easily, usually through a config setting
and without redeploying the app.
Design patterns for decoupling dependencies
Dependency Inversion and Injection
DI uses config and code to determine
dynamically the implementation that will
be used, decoupling dependencies from
where they are used.
In fact, the implementation
classes now could live in
separate packages or
namespaces than
ChatApp…
Now we’ve completely
decoupled the ChatApp
from the implementation
dependencies by looking up
at runtime what to use.
ChatApp
package
Vacation
package
Work
package
Base
package
ChatApp
package
Vacation
package
Scratch Org
Base
package
Sandbox
Use CMDT to
wire up which
IMessage impl
class to inject at
runtime via DI
Scratch Org
Scratch Org
Where does Injector.Org come from?
Introducing Force DI, an Open Source Dependency Injection Framework
Andy
Fawcett
John
Daniel
Doug
Ayers
Demo
Dependency injection using the force-di framework
Resources
Force-DI on GitHub
• https://github.com/afawcett/force-di
• Inspired by Google’s Guice library
Dependency Injection Sites
• Martin Fowler
• Derick Bailey (Los Techies)
• Thorben Janssen (Stackify)
• Wikipedia
Dreamforce Sessions
• Understanding the value of Dependency
Injection in the Lightning Platform
• Advanced Techniques To Adopt Salesforce DX
Unlocked Packages
• How Packaging Transformed App Dev
at CarMax
• Tips for Organizing Metadata to
Adopt Unlocked Packages
© Copyright 2018 salesforce.com, inc. All
rights reserved. Various trademarks held
by their respective owners.
Thanks for Attending!
What’s Next?
LEARN ALL THE SKILLS YOU NEED
Build on your skills with self-paced learning or another expert-led class.
https://sfdc.co/learnsalesforce
EARN SKILL-BASED CREDENTIALS
Get rewarded for the skills you learn and get industry-wide recognition
for your expertise.
https://trailhead.salesforce.com/en/superbadges
http://certification.salesforce.com/
CONNECT WITH FELLOW TRAILBLAZERS
Follow us in the Trailblazer Community, and on social.
Community: https://sfdc.co/TrailheadCommunity
Twitter: @Trailhead
Facebook: /SalesforceTrailhead
Dependency Injection with the Force DI Framework

More Related Content

Similar to Dependency Injection with the Force DI Framework (20)

PPTX
Enterprise-grade UI with open source Lightning Web Components
Salesforce Developers
 
PPTX
Building JavaScript Applications on the Salesforce1 Platform
Salesforce Developers
 
PDF
Building Lightning Components for ISVs (Dreamforce 2015)
Salesforce Partners
 
PPTX
Get Started with Salesforce DX!
Salesforce Developers
 
PDF
Make Your App Lightning Ready with Winter '17 (December 8, 2016)
Salesforce Partners
 
PPTX
Lightning Developer Experience, Eclipse IDE Evolved
Salesforce Developers
 
PDF
Intro to the Salesforce Mobile SDK: Building iOS Apps Webinar
Salesforce Developers
 
PDF
Enterprise Heroku for Java
Ayumu Aizawa
 
PPTX
TrailheaDX and Summer '19: Developer Highlights
Salesforce Developers
 
PDF
ISV Lightning Webinar Series - Part 2 (December 8, 2015)
Salesforce Partners
 
PDF
Build Apple Watch Apps for the Enterprise
Salesforce Developers
 
PDF
Salesforce DX Pilot Product Overview
Salesforce Partners
 
PPTX
Salesforce Lightning Design System
Durgesh Dhoot
 
PPTX
Go Faster with Lightning - Overview
Salesforce Developers
 
PPTX
Using Python on Heroku and Force.com Canvas to Enhance Salesforce.com
Salesforce Developers
 
PPTX
Lightning Components Introduction
Durgesh Dhoot
 
PDF
Lightning web components - Episode 1 - An Introduction
Salesforce Developers
 
PPTX
Winter '16 Release - Overview and Highlights
Salesforce Developers
 
PPTX
How to Shop Smart on AppExchange by Jenn Romaniszak
Salesforce Admins
 
PDF
Build Customer Centric Applications Using the Salesforce Toolkits for .NET
Salesforce Developers
 
Enterprise-grade UI with open source Lightning Web Components
Salesforce Developers
 
Building JavaScript Applications on the Salesforce1 Platform
Salesforce Developers
 
Building Lightning Components for ISVs (Dreamforce 2015)
Salesforce Partners
 
Get Started with Salesforce DX!
Salesforce Developers
 
Make Your App Lightning Ready with Winter '17 (December 8, 2016)
Salesforce Partners
 
Lightning Developer Experience, Eclipse IDE Evolved
Salesforce Developers
 
Intro to the Salesforce Mobile SDK: Building iOS Apps Webinar
Salesforce Developers
 
Enterprise Heroku for Java
Ayumu Aizawa
 
TrailheaDX and Summer '19: Developer Highlights
Salesforce Developers
 
ISV Lightning Webinar Series - Part 2 (December 8, 2015)
Salesforce Partners
 
Build Apple Watch Apps for the Enterprise
Salesforce Developers
 
Salesforce DX Pilot Product Overview
Salesforce Partners
 
Salesforce Lightning Design System
Durgesh Dhoot
 
Go Faster with Lightning - Overview
Salesforce Developers
 
Using Python on Heroku and Force.com Canvas to Enhance Salesforce.com
Salesforce Developers
 
Lightning Components Introduction
Durgesh Dhoot
 
Lightning web components - Episode 1 - An Introduction
Salesforce Developers
 
Winter '16 Release - Overview and Highlights
Salesforce Developers
 
How to Shop Smart on AppExchange by Jenn Romaniszak
Salesforce Admins
 
Build Customer Centric Applications Using the Salesforce Toolkits for .NET
Salesforce Developers
 

More from Doug Ayers (11)

PDF
TDX19 - Accelerate DevOps with GitLab and Salesforce
Doug Ayers
 
PDF
TDX19 - Untangle Your Org with Salesforce Developer Tools
Doug Ayers
 
PDF
Adopting Files and Enhanced Notes in Lightning Experience
Doug Ayers
 
PDF
Chatter Bot - Enabling New Capabilities for Process Builder
Doug Ayers
 
PPTX
Dreamforce '16 Recap & Winter '17 Release
Doug Ayers
 
PPTX
Salesforce - How to Load Leads and Add to Campaigns with Import Wizard
Doug Ayers
 
PPTX
Salesforce: Advanced Lead Conversion Using Process Builder
Doug Ayers
 
PPTX
Salesforce - The Power of Upsert and External IDs - How To - Workbench
Doug Ayers
 
PPTX
Salesforce - Filtered Related Lists Without Code
Doug Ayers
 
PPTX
Dreamforce 15 Recap & Winter 16 Release Notes
Doug Ayers
 
PPTX
Salesforce1 Mobile Experience - Remedyforce On Call
Doug Ayers
 
TDX19 - Accelerate DevOps with GitLab and Salesforce
Doug Ayers
 
TDX19 - Untangle Your Org with Salesforce Developer Tools
Doug Ayers
 
Adopting Files and Enhanced Notes in Lightning Experience
Doug Ayers
 
Chatter Bot - Enabling New Capabilities for Process Builder
Doug Ayers
 
Dreamforce '16 Recap & Winter '17 Release
Doug Ayers
 
Salesforce - How to Load Leads and Add to Campaigns with Import Wizard
Doug Ayers
 
Salesforce: Advanced Lead Conversion Using Process Builder
Doug Ayers
 
Salesforce - The Power of Upsert and External IDs - How To - Workbench
Doug Ayers
 
Salesforce - Filtered Related Lists Without Code
Doug Ayers
 
Dreamforce 15 Recap & Winter 16 Release Notes
Doug Ayers
 
Salesforce1 Mobile Experience - Remedyforce On Call
Doug Ayers
 
Ad

Recently uploaded (20)

PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PPTX
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PPTX
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
NewMind AI Weekly Chronicles – July’25, Week III
NewMind AI
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
RAT Builders - How to Catch Them All [DeepSec 2024]
malmoeb
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PPTX
AVL ( audio, visuals or led ), technology.
Rajeshwri Panchal
 
PPTX
Farrell_Programming Logic and Design slides_10e_ch02_PowerPoint.pptx
bashnahara11
 
PDF
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
The Future of Artificial Intelligence (AI)
Mukul
 
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
NewMind AI Weekly Chronicles – July’25, Week III
NewMind AI
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
RAT Builders - How to Catch Them All [DeepSec 2024]
malmoeb
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
AVL ( audio, visuals or led ), technology.
Rajeshwri Panchal
 
Farrell_Programming Logic and Design slides_10e_ch02_PowerPoint.pptx
bashnahara11
 
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
Ad

Dependency Injection with the Force DI Framework

  • 1. Dependency Injection Decoupling dependencies for flexible app design [email protected], @douglascayers Doug Ayers, Technical Curriculum Developer, Trailhead
  • 2. Doug Ayers Technical Curriculum Developer, Trailhead @douglascayers github.com/douglascayers douglascayers.com Developer, Educator, Blogger “The fun way to learn Salesforce”
  • 3. Exploring Use Cases for Dependency Injection https://www.meetup.com/ForceDotCom/events/253817247/ Look for recording to be posted to the Bay Area Salesforce Dev Group YouTube Channel
  • 4. Learn directly from Salesforce experts at #DF18 Bootcamp https://www.salesforce.com/dreamforce/certification/ Pre-Conference Bootcamp: Developing Applications using Salesforce DX and Heroku Pipelines • 3 Days • Instructor-Led • Hands-On • I’ll be there 😎
  • 5. This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services. The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of any litigation, risks associated with completed and any possible mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most recent fiscal quarter. These documents and others containing important disclosures are available on the SEC Filings section of the Investor Information section of our Web site. Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements. Statement under the Private Securities Litigation Reform Act of 1995 Forward-Looking Statement
  • 6. Agenda • What is dependency injection and what does it solve? • Walkthrough: refactoring tightly coupled code • Overview of force-di open source project • Demo force-di with Lightning, Visualforce, Apex, and Flows • Resources • Q&A
  • 7. What does Dependency Injection solve?
  • 8. What does Dependency Injection solve?
  • 9. Tight coupling of which message class to use.
  • 10. Introduce an interface so the concrete implementations can be swapped out. Move logic of which implementation to use, which decouples the greetings method from the message provider.
  • 11. Move logic of which implementation to use, which decouples the greetings method from the message provider. We can take this further by injecting the implementation to use at runtime, completely decoupling the classes.
  • 12. Now we’ve completely decoupled the ChatApp from the implementation dependencies by looking up at runtime what to use. Two flavors of constructor injection by either passing in the class to use or looking it up in real-time.
  • 13. Design patterns for decoupling dependencies Dependency Inversion and Injection An app codes to interfaces so that behavior can be swapped out with little to no code changes to the app.
  • 14. Design patterns for decoupling dependencies Dependency Inversion and Injection Implementations can be swapped out easily, usually through a config setting and without redeploying the app.
  • 15. Design patterns for decoupling dependencies Dependency Inversion and Injection DI uses config and code to determine dynamically the implementation that will be used, decoupling dependencies from where they are used.
  • 16. In fact, the implementation classes now could live in separate packages or namespaces than ChatApp… Now we’ve completely decoupled the ChatApp from the implementation dependencies by looking up at runtime what to use.
  • 18. ChatApp package Vacation package Scratch Org Base package Sandbox Use CMDT to wire up which IMessage impl class to inject at runtime via DI Scratch Org Scratch Org
  • 19. Where does Injector.Org come from? Introducing Force DI, an Open Source Dependency Injection Framework Andy Fawcett John Daniel Doug Ayers
  • 20. Demo Dependency injection using the force-di framework
  • 21. Resources Force-DI on GitHub • https://github.com/afawcett/force-di • Inspired by Google’s Guice library Dependency Injection Sites • Martin Fowler • Derick Bailey (Los Techies) • Thorben Janssen (Stackify) • Wikipedia Dreamforce Sessions • Understanding the value of Dependency Injection in the Lightning Platform • Advanced Techniques To Adopt Salesforce DX Unlocked Packages • How Packaging Transformed App Dev at CarMax • Tips for Organizing Metadata to Adopt Unlocked Packages
  • 22. © Copyright 2018 salesforce.com, inc. All rights reserved. Various trademarks held by their respective owners. Thanks for Attending! What’s Next? LEARN ALL THE SKILLS YOU NEED Build on your skills with self-paced learning or another expert-led class. https://sfdc.co/learnsalesforce EARN SKILL-BASED CREDENTIALS Get rewarded for the skills you learn and get industry-wide recognition for your expertise. https://trailhead.salesforce.com/en/superbadges http://certification.salesforce.com/ CONNECT WITH FELLOW TRAILBLAZERS Follow us in the Trailblazer Community, and on social. Community: https://sfdc.co/TrailheadCommunity Twitter: @Trailhead Facebook: /SalesforceTrailhead

Editor's Notes

  • #6: Key Message Salesforce is a publicly traded company. Customers should make buying decisions only on the products commercially available. Talk Track Before I begin, just a quick note that you should base your purchasing decisions on products and services that are currently available.
  • #8: https://stackoverflow.com/questions/14301389/why-does-one-use-dependency-injection Often code classes depend on each other, such as an Apex controller depending on another Apex class to log metrics and information. Overtime, you create many Apex classes that use the same logger, which persists the metrics to a custom object. Later, you decide you want to log the metrics to a third-party system rather than a custom object. To make this change, you need to search and replace your code base and re-deploy your app. Later, you decide you need to log via http callouts in some places, to log via platform events in other places, and to make testing easier to use mock loggers in yet other places. Dependency injection is a design pattern that decouples code from its dependencies by following a couple key principles: Code to interfaces (abstractions) rather than referencing implementation classes directly Use a service locator to look up dynamically and inject the appropriate interface implementation, whereby the actual implementation can be swapped out via simple configuration settings and no code changes There also exists declarative dependencies such as when a custom button depends on a specific Visualforce page or Lightning component to invoke.
  • #9: https://stackoverflow.com/questions/14301389/why-does-one-use-dependency-injection When you first develop an application, you begin with your requirements and everything you put into the app has a known purpose. All the parts and pieces have their place and the app ”just works”.
  • #10: https://stackoverflow.com/questions/14301389/why-does-one-use-dependency-injection Overtime, however, you may receive new requirements that build on top of or contradict the original design. Like playing the game Jenga, refactoring the app to support these changes can be tough. Depending on the architecture, such as tightly coupled code, then making changes can be difficult and potentially cause breaking changes. The more tweaks to the code to try and bend original design to new requirements often leads to messy code. Dependency injection is a design pattern to try and mitigate those risks by using architectures that are loosely coupled and implementation details can be swapped out in a more of plug-n-play manner without causing significant changes to other parts of the code base.
  • #11: Animations: Click to show bottom orange rectangle around message classes Click to show top orange rectangle around chat app Click to show the apex debug code output We start with three simple classes, ChatApp, WorkingMessage, and VacationMessage. There is nothing inherently wrong with this design. Firstly, do note that ChatApp is tightly coupled to both the WorkingMessage and VacationMessage classes. If the message classes change, then that likely will require changes to ChatApp. Secondly, for the ChatApp class to compile, then both the messaging classes must also exist in the same org. Thirdly, to change out what message is used when the user is in or out of office requires the Apex classes to be updated and re-deployed.
  • #12: Animations: Click to highlight the IMessage interface in lower region of slide Click to highlight the IMessage usage in ChatApp Click to highlight the ChatApp constructor Our first refactoring step is to introduce an interface, IMessage, and update the WorkingMessage and VacationMessage classes to implement it. Next, we update ChatApp’s greetings() method to code against the interface rather than knowing the specific implementation class. In this manner, we have decoupled the greetings() method from the details. In this example, we have moved the logic for determing the message implementation to use into the constructor, a logical next step would be to either modify the constructor to accept an IMessage argument (this is known as constructor injection) or have the constructor use a service locator to look up the implementation to use. Either way, the next step is to decouple the ChatApp entirely from knowing about the IMessage implementations and only know about the interface (the abstraction).
  • #13: In this example, we have moved the logic for determing the message implementation to use into the constructor, a logical next step would be to either modify the constructor to accept an IMessage argument (this is known as constructor injection) or have the constructor use a service locator to look up the implementation to use. Either way, the next step is to decouple the ChatApp entirely from knowing about the IMessage implementations and only know about the interface (the abstraction).
  • #14: In this example, we have moved the logic for determing the message implementation to use into the constructor, a logical next step would be to either modify the constructor to accept an IMessage argument (this is known as constructor injection) or have the constructor use a service locator to look up the implementation to use. Either way, the next step is to decouple the ChatApp entirely from knowing about the IMessage implementations and only know about the interface (the abstraction).
  • #15: Animations: 1. Click to show the textbox Let’s step back from the code for a minute and talk about what we have developed with our refactoring efforts. In the orange box, we have our ChatApp with a greetings() method and an IMessage property that refers to an interface in the blue box. In the green boxes, we have two implementations of the IMessage interface that can be injected into the ChatApp. Designing your apps to code to interfaces (abstractions) is the first step to decoupling dependencies from the code that uses them.
  • #16: Because ChatApp’s operations do not specifically refer to the message implementations, then we can add/update/remove green boxes without causing code changes to the orange box (our application).
  • #17: Then, for even more flexibility in our app’s design, we can dynamically determine the implementation class to use with a dependency injection framework that either looks up the class to use in configuration or runs custom Apex logic to determine the class the use.
  • #18: Animation: 1. Click to highlight the bottom message classes Let’s come back to the code again and begin to think about the benefits this design has when we look to packaging our app.
  • #19: Because our ChatApp is decoupled from the VacationMessage and WorkMessage classes, they can each be developed and live in their own packages. The ony common dependency among them is a base package with the IMessage interface.
  • #20: Animations: Click to show sandbox cloud Click to show green line draw to sandbox Click to show orange line draw to sandbox Click to show purple line draw to sandbox Click to show CMDT text box For development purposes, we could have different teams working on the separate packages in their own scratch orgs. Then when ready to do some integration testing, they can install their packages into a sandbox. Use a dependency injection framework or similar logic to then look up and inject into ChatApp the desired message implementation class.
  • #21: https://github.com/afawcett/force-di
  • #22: Demo 1: The ChatApp example discussed in the slides Open developer console and show the refactored code using the force-di framework Create a CMDT record to wire up VacationMessage as the message class to inject Run anonymous apex to show the debug output printed the out of office message Update the CMDT record to wire up WorkingMessage as the message class to inject Run anonymous apex to show the debug output printed the in the office message Demo 2: Object Action Override with Lightning component In Object Manager, show the Widget__c object’s View action overridden with a lightning component Open developer console to show the WidgetNewCmp using the <c:di_injector> tag Create a CMDT record to wire up VacationMessage as the message class to inject Demo 3:
  • #24: End Slide