Services
Step-by-step guide on how to set up and interact with a Service, maximise the functions and benefits, while being aware of edge cases and D'fflib specific functionalities.
Characteristics
A Service holds the business logic that doesn't fit a single SObject: processes spanning multiple SObjects, reusable logic, and integrations in or out. It does the work, without knowing who started it. Think of it as a Specialist for one process, which owns that single-responsibility end-to-end.
Responsibilities
Services have a wide variety of responsibilities of which main are:
Split heavy processes into modular classes, respecting separation of concerns and maintainability.
Relates to Domain-Service ambiguity (→ Overview page).
Multiple Services per process are valid, like SRV_OpportunityRenewal and SRV_OpportunityMACD living side by side with a lean DOM_Opportunities.
Interactions
| Interaction | Layers |
|---|---|
| Called by | API, Entrypoints, Batch execute(), other Services (with caution) |
| Calling | Selectors, Domains, Services, Unit of Work |
Technically, a Service can be both the caller (e.g. for an incoming integration) and the callee. Due to this dual role, this is the only layer that, with caution, may call other instances of its own layer. The precaution is to avoid circular dependencies and unintended side effects from multiple Service instances interacting in complex ways.
Depending on the role, Services only register the relevant records to a received input-Unit of Work without committing (e.g. outgoing integration), however, for incoming integrations it is expected to initiate and control the Unit of Work internally. Similar to other layers, it remains important for Services to be caller-agnostic and never assume the context in which they are invoked.
Rules
- Methods should have a clear single responsibility.
- Methods should be robust and satisfy the open-close principle.
- Methods should be caller agnostic, thus not assume any context of the caller, e.g. throw Exceptions instead of emitting user-facing messages.
- Methods should be bulkified and accept a
Set<Id>orList<SObject>as input to be scalable and reusable. - Generally Services run
with sharing, given the users running business processes. However, due to agnostic natureinherited sharingmight fit better.
When being called:
- The Service only registers and doesn't commit (even no Log records), e.g. to avoid 'uncommitted work pending' errors for integrations.
Initiation
How to call
Comparable to other layers, Services are instantiated via newInstance(), enabling mocking.
// Entrypoint owns the UoW construction and the commit
dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance();
SRV_RoomReservations.newInstance().confirmReservation( reservationIds, uow );
uow.commitWork();The framework factory (dfflib.service) will:
- Check whether a mock-instance was set and return if available
- Retrieve the related
Dfflib_Service_Config__mdtmetadata - Instantiate the Service class with the retrieved configuration.
- Return the constructed Service class-instance.
Theoretically, it is possible to call dfflib.service.newInstance() directly to avoid the static newInstance() boilerplate in your Service.
However, you'll need to cast its generic Object result that the Service class would otherwise cast centrally.
Regardless of choice, the recommendation is to be consistent throughout your codebase.
SRV_RoomReservations serviceDirect = ( SRV_RoomReservations ) dfflib.service.newInstance( SRV_RoomReservations.class );Class boilerplate
Unlike the other layers, the Service class requires only a static newInstance() method to function.
Which is even obsolete for an incoming API Service class, as this class is not expected to be instantiated nor referenced
within your own codebase.
public with sharing class SRV_RoomReservations{
public static SRV_RoomReservations newInstance(){
return ( SRV_RoomReservations ) dfflib.service.newInstance( SRV_RoomReservations.class );
}
// Service methods and implementation....
}@RestResource( UrlMapping = '/Room/Cancellation/*' )
global with sharing class SRVi_RoomCancellation{
@HttpPost
global static void handleRequest(){
// Integration magic
}
}Service Interface isn't a framework requirement
There is no framework need to construct an interface like IService. Examples including such, predate the Apex Stub API to enable mocking.
However, a Service could be likely to desire different implementations in the future (e.g. SRV_OpportunityRenewal for country or product family
differentiations), where such interface would allow swapping implementations without changing the consuming code, leveraging dependency injection.
This is thus a project- and business-specific need, not a framework mandate.
The naming in the metadata is a legacy convention and does not imply a strict requirement for an interface to exist.
Metadata registration
To ensure the newInstance() factory method resolves the correct class, the Service must be registered in the Dfflib_Service_Config__mdt
custom metadata type . With the right AI skills, this metadata file can be automatically generated, else ensure to set the below values:
| Field | Purpose | Example |
|---|---|---|
MasterLabel | Label of the mdt record. Shown in Setup | SRV_RoomReservations |
DeveloperName | Unique API name of the record. Doesn't allow duplicate (___) thus namespace with single | SRV_RoomReservations |
Interface_Type__c | Interface the Service is resolved by | SRV_RoomReservations or SRV_RoomReservations.IService |
Implementation_Type__c | Class implementing the Service | SRV_RoomReservations |
Code examples
Since the Service layer isn't much more than a mockable layer, there are no standard or advanced methods to leverage.
Every code-example we'd give is more a possible business process illustration than a strict guideline on how to leverage the Service layer.
Below are therefore some examples of what a Service class might look like in practice, like SRVo_PostalCodeValidation.
| Class | Context |
|---|---|
| SRV_Request | HTTP request builder |
| SRV_Response | Standardised LWC & HTTP Response builder |
| SRVo_PostalCodeValidation | Outgoing integration to validate postal codes |
| SRVo_PostalCodeValidationTest | Unit test for outgoing integration |
Migration steps
For existing code to leverage D'fflib features, a couple migration steps are required. Below steps apply once D'fflib extensions are installed (Getting Started).
Required changes
- Ensure
Dfflib_Service_Config__mdtrecord exists - Change
[Application].service.newInstance()todfflib.service.newInstance()
public with sharing class SRVo_PostalCodeValidation{
public static SRVo_PostalCodeValidation newInstance(){
return ( SRVo_PostalCodeValidation ) dfflib.service.newInstance( SRVo_PostalCodeValidation.class );
}
}public with sharing class SRVo_PostalCodeValidation{
public static SRVo_PostalCodeValidation newInstance(){
return ( SRVo_PostalCodeValidation ) Application.service.newInstance( SRVo_PostalCodeValidation.class );
}
}Selectors
Step-by-step guide on how to set up and interact with a Selector, maximise the functions and benefits, while being aware of edge cases and D'fflib specific functionalities.
Testing & Mocking
Elaborating on the benefits of mocking, and how to properly set up test data to mock methods with. Including thorough and extensive example code snippets.