0% found this document useful (0 votes)
16 views8 pages

Salesforce Apex Dependency Injection

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views8 pages

Salesforce Apex Dependency Injection

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

@deedev

Mastering Salesforce Apex

What Is
Dependency
Injection
Pattern ?
@deedev
01

What is DI ?
Dependency Injection is a design pattern
that allows a class to receive its
dependencies from external sources
rather than creating them internally.
In a typical Sales Cloud implementation, you
might have a trigger that sends notifications
to customers when their opportunity reaches
a certain stage. Over time, the notification
method may change—from email to SMS to
push notifications. You want to design your
system so that it can easily adapt to these
changes without rewriting significant portions
of your code.
@deedev
02
How Does Dependency Injection Work?
At its core, Dependency Injection involves three
components:
1. Client Class: The class that depends on
external services (dependencies) to function.
2. Service Interface: An abstraction that defines
the methods the dependency must implement.
3. Injector: The mechanism by which the
dependency is provided to the client class.

Injection Methods:
Constructor Injection: Dependencies are provided
through the class constructor.
Setter Injection: Dependencies are assigned through
setter methods.
Interface Injection: Dependencies are injected via an
interface method.
@deedev
03
Implementing Dependency Injection in
Apex
Create an interface that outlines the methods
any notification service must implement.
@deedev
04
Email Notification Service:
Create classes that implement the interface
for different notification methods. In this
implementation, we will take a look at Email
Notification, in similar manner you can
create SMS notification class and inject it on
runtime.
@deedev
05
Client Class to Accept
Dependencies
Update your main class to accept an
INotificationService implementation.
@deedev
06
Use Dependency Injection in Your
Trigger
Similar to this Email Notification, you can
create a SMS Service class which will be used
to switch the notification method when
required. No changes are needed in the
OpportunityNotifier class when switching
services!
@deedev

Did you find


this useful ?
d b a ck !
r y an d s hare fee
ive it a t
G

You might also like