This repository demonstrates Apex Dependency Injection with a sample shipping service (ShippingService
) that allows to generate tracking numbers.
This sample provides two shipping service mock implementations: FedExImpl
and DHLImpl
.
The service can be accessed via the ShippingInjector
class in two ways:
Option 1: Using the default implementation
This requires that you set the default service implementation as a Service_Implementations__mdt
custom metadata record. The Shipping__c
field of the custom metadata record must map to one of the ShippingService
implementation class names.
// Get the implementation of the service configured in Service_Implementations__mdt.Shipping__c custom metadata
ShippingService service = ShippingInjector.getDefaultService();
String trackingNumber = service.generateTrackingNumber();
System.debug(trackingNumber); // => DHL-XXXX if DHLImpl is the default
Option 2: Using a specific implementation
// Get the FedEx implementation
ShippingService service = ShippingInjector.getService('FedExImpl');
String trackingNumber = service.generateTrackingNumber();
System.debug(trackingNumber); // => FEX-XXXX
-
Create a scratch org:
sfdx force:org:create -a apex-di -s -f config/project-scratch-def.json
-
Push source to scratch org:
sfdx force:source:push