Domain Process Injection

Injecting criteria and actions into domain logic — the only two things AT4DX injects into a domain process.

Domain Process Injection separates two questions that domain logic always has to answer: which records qualify? and what work should be done on them? In traditional domain code these questions are interleaved in if/else chains. In AT4DX they are separate classes wired together by metadata — and in the most common case, the domain class itself contains no code at all.

The Core Concept

A Criteria class answers the first question. It receives a record set, evaluates each record against a rule, and returns the matching subset. It does not perform DML or call services — it just filters. Criteria implement IDomainProcessCriteria.

An Action class answers the second question. It receives the records that survived criteria filtering and performs work: mutating field values, registering records with a Unit of Work, enqueuing jobs, publishing platform events. Actions extend DomainProcessAbstractAction.

DomainProcessBinding__mdt is the metadata that wires them together. Each binding record is either a Criteria or an Action (Type__c), names the class to run (ClassToInject__c), and says when it should run — which SObject (RelatedDomainBindingSObject__c), in which context (ProcessContext__c), and for which trigger operation (TriggerOperation__c).

DomainProcessCoordinator is the runtime engine that reads those bindings and runs the Criteria → Action pipeline. You rarely call it directly — ApplicationSObjectDomain invokes it for you.


You Usually Write No Domain Code

This is the single most important thing to understand, and it is what makes AT4DX different from hand-rolled fflib domains.

ApplicationSObjectDomain (the base class every AT4DX domain extends) already overrides the fflib handle* lifecycle methods — handleBeforeInsert, handleBeforeUpdate, handleAfterInsert, handleAfterUpdate, handleAfterDelete, etc. Each override calls super.handle*() and then asks the coordinator to run matching DomainProcessBinding__mdt records.

// Inside ApplicationSObjectDomain (framework code — you do NOT write this).
// AT4DX hooks the fflib handle* methods: it calls super (which runs any on* logic),
// then invokes the coordinator for that operation.
public virtual override void handleAfterUpdate(Map<Id, SObject> existingRecords) {
    super.handleAfterUpdate(existingRecords);
    this.getDomainProcessCoordinator().processDomainLogicInjections(
        DomainProcessConstants.PROCESS_CONTEXT.TriggerExecution,
        System.TriggerOperation.After_Update,
        existingRecords
    );
}

So to add behavior to a trigger, you do not override onAfterUpdate and you do not instantiate DomainProcessCoordinator. You:

  1. Write a Criteria class and/or an Action class.
  2. Deploy DomainProcessBinding__mdt records that point at them.

The domain class stays empty (aside from its constructor and Constructor inner class). New rules arrive as new metadata records — often from a different package — and the domain never changes.

There is a second context, DomainMethodExecution, for invoking criteria/actions from your own domain method (not a trigger). That case does involve calling the coordinator, and it is covered at the end of this page.


Why This Pattern Matters

Consider what Account domain logic looks like without this pattern:

public override void onAfterUpdate(Map<Id, SObject> existing) {
    List<Account> largeAccounts = new List<Account>();
    for (Account acct : (List<Account>) getRecords()) {
        if (acct.AnnualRevenue > 1000000) {
            largeAccounts.add(acct);
        }
    }
    if (!largeAccounts.isEmpty()) {
        for (Account a : largeAccounts) { a.Status__c = 'Strategic'; }
        // ... enqueue notifications, more conditions as new requirements arrive
    }
}

As requirements grow, this method becomes the coordination point for everything. Adding a rule means modifying this class, redeploying its package, and colliding with every other team whose code runs in this trigger.

With Domain Process Injection the domain is empty and each rule is an isolated class deployed by whichever package owns it.

Additional benefits:


The Interfaces and Base Classes

IDomainProcessCriteria

public interface IDomainProcessCriteria {
    IDomainProcessCriteria setRecordsToEvaluate(List<SObject> records);
    List<SObject> run();
}

Implement this for any class that filters records. The coordinator calls setRecordsToEvaluate(...) with the records to inspect, then run(), which returns only those that match.

DomainProcessAbstractAction

public abstract class DomainProcessAbstractAction
    implements IDomainProcessAction, IDomainProcessUnitOfWorkable, IDomainProcessQueueableAction {

    // Populated by the coordinator before runInProcess() is called:
    protected List<SObject> records = new List<SObject>();
    protected IApplicationSObjectUnitOfWork uow = null;

    // You implement this:
    public abstract void runInProcess();

    // Coordinator calls these for you — you normally don't:
    public IDomainProcessAction setRecordsToActOn(List<SObject> records) { ... }
    public IDomainProcessUnitOfWorkable setUnitOfWork(IApplicationSObjectUnitOfWork uow) { ... }
}

Extend this class for any class that performs work. Override runInProcess() and read the protected fields directly: this.records for the criteria-filtered set, and this.uow for the Unit of Work.

Important: there are no getRecords() / getUnitOfWork() accessor methods. Use the protected records and uow fields.

Also important: this.uow is only populated when the coordinator is given a UnitOfWork. In trigger context the framework passes no UoW, so this.uow is null there. That is fine for before-trigger actions, which mutate this.records in place (those changes persist with no DML). If an after-trigger action needs to make DML against other records, create or pass a UnitOfWork explicitly (see the DomainMethodExecution pattern below).


How the Coordinator Runs: Sequences

When the coordinator runs, it gathers every active binding matching the SObject + context + trigger operation, then groups them into sequences.

A sequence is the integer part of OrderOfExecution__c. Every binding whose OrderOfExecution__c has the same integer portion belongs to the same sequence. Within each sequence:

  1. All Criteria run first, sorted by OrderOfExecution__c. They chain: the first criteria filters the full record set, the second filters that result, and so on (progressive AND filtering). LogicalInverse__c = true flips a criteria so matching records are removed instead of kept.
  2. Then all Actions run, sorted by OrderOfExecution__c, each receiving the final surviving record set.
  3. Each sequence starts over from the full domain record set before filtering.

This last point is critical: two mutually-exclusive rules (e.g. "large accounts" and "small accounts") must live in separate sequences, because every sequence re-filters the complete record set independently. Putting LargeAccountCriteria and SmallAccountCriteria in the same sequence would AND them together and match nothing.

A convenient convention is to encode the sequence in the integer part and the in-sequence order in the decimal part — e.g. 10.10 (criteria), 10.20 (action) form sequence 10; 20.10, 20.20 form sequence 20.

OrderOfExecution__c is a Number(4,2) field, so deployed values run 0.00–99.99: the sequence (integer part) is 0–99, and the two decimal places order bindings within a sequence. (In-memory mock bindings built in a test aren't bound by this, but anything you deploy is.)

flowchart TD
    T([Trigger: Account after update]) --> B[ApplicationSObjectDomain.handleAfterUpdate]
    B --> C[DomainProcessCoordinator: load active DomainProcessBinding__mdt<br/>for Account + TriggerExecution + After_Update]
    C --> G[Group bindings into sequences by Integer.valueOf OrderOfExecution__c]
    G --> S1
    G --> S2
    subgraph S1[Sequence 10]
      direction TB
      S1C[Criteria by OrderOfExecution: chain-filter from full record set] --> S1A[Actions by OrderOfExecution: run on survivors]
    end
    subgraph S2[Sequence 20]
      direction TB
      S2C[Criteria: chain-filter from full record set again] --> S2A[Actions: run on survivors]
    end

Complex Multi-SObject Flow

The following example shows 21 injected classes across Account, Opportunity, Case, and Contact. Each boxed sequence is independent and begins with the full record set for that domain invocation. Criteria within a sequence progressively AND-filter the records; every Action in that sequence receives the final survivors.

flowchart LR
    subgraph ACCOUNT[Account — After_Update]
        direction TB
        AF1[(all Accounts)] --> AC1[10.10 LargeAccountCriteria]
        AC1 --> AC2[10.20 TargetRegionCriteria]
        AC2 --> AA1[10.30 MarkStrategicAccountAction]
        AC2 --> AA2[10.40 NotifySalesDirectorAction]
        AC2 --> AA3[10.50 CreateAccountReviewAction]

        AF2[(all Accounts again)] --> AC3[20.10 DormantAccountCriteria]
        AC3 --> AA4[20.20 FlagDormantAccountAction]
        AC3 --> AA5[20.30 EnqueueNurtureAction]
    end

    subgraph OPPORTUNITY[Opportunity — After_Update]
        direction TB
        OF[(all Opportunities)] --> OC1[10.10 HighValueOpportunityCriteria]
        OC1 --> OC2[10.20 ClosingThisQuarterCriteria]
        OC2 --> OC3[10.30 MissingExecutiveSponsorCriteria]
        OC3 --> OA1[10.40 CreateExecutiveSponsorTaskAction]
        OC3 --> OA2[10.50 NotifyRegionalVPAction]
    end

    subgraph CASE[Case — After_Update]
        direction TB
        CF[(all Cases)] --> CC1[10.10 BreachedSLACriteria]
        CC1 --> CC2[10.20 HighPriorityCaseCriteria]
        CC2 --> CA1[10.30 EscalateCaseAction]
        CC2 --> CA2[10.40 NotifySupportManagerAction]
        CC2 --> CA3[10.50 PageOnCallEngineerAction]
    end

    subgraph CONTACT[Contact — After_Update]
        direction TB
        CTF[(all Contacts)] --> CTC1[10.10 EmailOptedInCriteria]
        CTC1 --> CTC2[10.20 NoRecentEngagementCriteria]
        CTC2 --> CTA1[10.30 EnqueueReengagementAction]
    end

The graph deliberately includes both relationship shapes:

Representative bindings are:

SObject / operation Sequence Criteria in order Actions in order
Account / After_Update 100 LargeAccountCriteria, TargetRegionCriteria MarkStrategicAccountAction, NotifySalesDirectorAction, CreateAccountReviewAction
Account / After_Update 200 DormantAccountCriteria FlagDormantAccountAction, EnqueueNurtureAction
Opportunity / After_Update 100 HighValueOpportunityCriteria, ClosingThisQuarterCriteria, MissingExecutiveSponsorCriteria CreateExecutiveSponsorTaskAction, NotifyRegionalVPAction
Case / After_Update 100 BreachedSLACriteria, HighPriorityCaseCriteria EscalateCaseAction, NotifySupportManagerAction, PageOnCallEngineerAction
Contact / After_Update 100 EmailOptedInCriteria, NoRecentEngagementCriteria EnqueueReengagementAction

Order values only group bindings that already match the same SObject, process context, and operation. Sequence 100 for Account does not interact with sequence 10 for Case. Actions that create or update other SObjects can use a supplied AT4DX UoW and call this.uow.register(recordsToStage); that does not change which domain's records were filtered.


Sales Example: Revenue Tier Processing

Scenario: When an Account is inserted or updated, classify it as Strategic (AnnualRevenue > $1M) or Standard, set Status__c, and for Strategic accounts enqueue an external notification.

Because Strategic and Standard are mutually exclusive, they go in two sequences.

Step 1: Criteria

// Package: sales-app
public class LargeAccountCriteria implements IDomainProcessCriteria {
    private List<Account> records;

    public IDomainProcessCriteria setRecordsToEvaluate(List<SObject> records) {
        this.records = (List<Account>) records;
        return this;
    }

    public List<SObject> run() {
        List<SObject> matched = new List<SObject>();
        for (Account acct : records) {
            if (acct.AnnualRevenue != null && acct.AnnualRevenue > 1000000) {
                matched.add(acct);
            }
        }
        return matched;
    }
}
// Package: sales-app
public class SmallAccountCriteria implements IDomainProcessCriteria {
    private List<Account> records;

    public IDomainProcessCriteria setRecordsToEvaluate(List<SObject> records) {
        this.records = (List<Account>) records;
        return this;
    }

    public List<SObject> run() {
        List<SObject> matched = new List<SObject>();
        for (Account acct : records) {
            if (acct.AnnualRevenue == null || acct.AnnualRevenue <= 1000000) {
                matched.add(acct);
            }
        }
        return matched;
    }
}

Criteria are pure functions — no DML, no service calls, no side effects.

Step 2: Synchronous Actions

These run in before context, so they mutate this.records directly and need no Unit of Work — the changes persist automatically as part of the trigger save.

// Package: sales-app
public class MarkStrategicAccountAction extends DomainProcessAbstractAction {
    public override void runInProcess() {
        for (SObject record : this.records) {
            ((Account) record).Status__c = 'Strategic';
        }
    }
}

public class MarkStandardAccountAction extends DomainProcessAbstractAction {
    public override void runInProcess() {
        for (SObject record : this.records) {
            ((Account) record).Status__c = 'Standard';
        }
    }
}

Step 3: Asynchronous Action

An async action must implement IDomainProcessQueueableAction; DomainProcessAbstractAction already does. The coordinator runs it asynchronously only when its binding has ExecuteAsynchronous__c = true. It receives the criteria-filtered records the same way (this.records).

// Package: sales-app
public class NotifyExternalSystemAction extends DomainProcessAbstractAction {
    public override void runInProcess() {
        List<Account> strategicAccounts = (List<Account>) this.records;
        // Build a payload and call an external system. Because this action's binding
        // sets ExecuteAsynchronous__c = true, the coordinator runs it in a queueable.
        System.enqueueJob(new AccountNotificationQueueable(strategicAccounts));
    }
}

public class AccountNotificationQueueable implements Queueable, Database.AllowsCallouts {
    private List<Account> accounts;
    public AccountNotificationQueueable(List<Account> accounts) {
        this.accounts = accounts;
    }
    public void execute(QueueableContext ctx) {
        // Call external REST API, publish platform event, etc.
    }
}

The async notification fires for Strategic accounts, so its binding lives in the same sequence as LargeAccountCriteria and runs after MarkStrategicAccountAction.

Step 4: Binding Metadata

The bindings are the wiring. Note: no domain code is written for any of this. These are custom metadata records, normally source-controlled as .md-meta.xml files; the field/value view is shown here for readability.

Sequence 10 — Strategic accounts (Account, TriggerExecution, After_Update)

  DomainProcessBinding__mdt — LargeAccountCriteria
    Type__c:                         Criteria
    ClassToInject__c:                LargeAccountCriteria
    RelatedDomainBindingSObject__c:  Account
    ProcessContext__c:               TriggerExecution
    TriggerOperation__c:             After_Update
    OrderOfExecution__c:             10.10
    IsActive__c:                     true

  DomainProcessBinding__mdt — MarkStrategicAccountAction
    Type__c:                         Action
    ClassToInject__c:                MarkStrategicAccountAction
    RelatedDomainBindingSObject__c:  Account
    ProcessContext__c:               TriggerExecution
    TriggerOperation__c:             After_Update
    OrderOfExecution__c:             10.20
    IsActive__c:                     true

  DomainProcessBinding__mdt — NotifyExternalSystemAction (async)
    Type__c:                         Action
    ClassToInject__c:                NotifyExternalSystemAction
    RelatedDomainBindingSObject__c:  Account
    ProcessContext__c:               TriggerExecution
    TriggerOperation__c:             After_Update
    OrderOfExecution__c:             10.30
    ExecuteAsynchronous__c:          true
    IsActive__c:                     true

Sequence 20 — Standard accounts (Account, TriggerExecution, After_Update)

  DomainProcessBinding__mdt — SmallAccountCriteria
    Type__c:                         Criteria
    ClassToInject__c:                SmallAccountCriteria
    RelatedDomainBindingSObject__c:  Account
    ProcessContext__c:               TriggerExecution
    TriggerOperation__c:             After_Update
    OrderOfExecution__c:             20.10
    IsActive__c:                     true

  DomainProcessBinding__mdt — MarkStandardAccountAction
    Type__c:                         Action
    ClassToInject__c:                MarkStandardAccountAction
    RelatedDomainBindingSObject__c:  Account
    ProcessContext__c:               TriggerExecution
    TriggerOperation__c:             After_Update
    OrderOfExecution__c:             20.20
    IsActive__c:                     true

Here is one of those records as the source-tracked XML you would actually commit:

<!-- sfdx-source/sales-app/main/customMetadata/DomainProcessBinding.LargeAccountCriteria.md-meta.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<CustomMetadata xmlns="http://soap.sforce.com/2006/04/metadata">
    <label>Large Account Criteria</label>
    <values><field>Type__c</field><value xsi:type="xsd:string">Criteria</value></values>
    <values><field>ClassToInject__c</field><value xsi:type="xsd:string">LargeAccountCriteria</value></values>
    <values><field>RelatedDomainBindingSObject__c</field><value xsi:type="xsd:string">Account</value></values>
    <values><field>ProcessContext__c</field><value xsi:type="xsd:string">TriggerExecution</value></values>
    <values><field>TriggerOperation__c</field><value xsi:type="xsd:string">After_Update</value></values>
    <values><field>OrderOfExecution__c</field><value xsi:type="xsd:double">10.10</value></values>
    <values><field>IsActive__c</field><value xsi:type="xsd:boolean">true</value></values>
</CustomMetadata>

To also classify accounts on insert, deploy a parallel set of bindings with TriggerOperation__c = After_Insert.

Step 5: The Domain (Empty)

The domain only needs to exist and be registered (see Application Factory Injection). It contains no onAfterUpdate override — the base class already drives the coordinator.

// Package: org-common — the one Account domain
public class AccountDomain extends ApplicationSObjectDomain {
    public AccountDomain(List<SObject> records) {
        super(records);
    }

    public class Constructor implements fflib_SObjectDomain.IConstructable {
        public fflib_SObjectDomain construct(List<SObject> records) {
            return new AccountDomain(records);
        }
    }
    // No trigger overrides. The DomainProcessBinding__mdt records drive everything.
}

Order of Operations

sequenceDiagram
    participant T as AccountTrigger
    participant D as ApplicationSObjectDomain<br/>(AccountDomain)
    participant C as DomainProcessCoordinator
    participant LC as LargeAccountCriteria
    participant MA as MarkStrategicAccountAction
    participant NA as NotifyExternalSystemAction
    participant SC as SmallAccountCriteria
    participant MB as MarkStandardAccountAction

    T->>D: after update (via fflib_SObjectDomain.triggerHandler)
    D->>C: processDomainLogicInjections(TriggerExecution, After_Update, existing)
    C->>C: Load active bindings for Account/After_Update, group into sequences
    Note over C: Sequence 10
    C->>LC: setRecordsToEvaluate(all records) → run() → [large accounts]
    C->>MA: setRecordsToActOn([large]) → runInProcess() (sets Status__c='Strategic')
    C->>NA: setRecordsToActOn([large]) → ExecuteAsynchronous__c → enqueued
    Note over C: Sequence 20 (re-filters full record set)
    C->>SC: setRecordsToEvaluate(all records) → run() → [small accounts]
    C->>MB: setRecordsToActOn([small]) → runInProcess() (sets Status__c='Standard')

Key behaviors:


Progressive Filtering Within a Sequence

Within one sequence you can chain multiple Criteria for progressive AND filtering — the output of each feeds the next:

Sequence 10:
  Criteria (10.10): LargeAccountCriteria       → accounts with AnnualRevenue > 1M
  Criteria (10.20): AccountInTargetRegion      → of those, the ones also in Region X
  Action   (10.30): NotifyTargetAccounts       → only accounts that are both large AND in region

Set LogicalInverse__c = true on a criteria to exclude its matches instead of keeping them.


Testing in Isolation

Each class is small enough to test independently.

Test a Criteria class — no database, no metadata:

@IsTest
static void largeAccountCriteria_returnsOnlyLargeAccounts() {
    List<SObject> testAccounts = new List<SObject>{
        new Account(Name = 'SmallCo', AnnualRevenue = 500000),
        new Account(Name = 'BigCo',   AnnualRevenue = 2000000),
        new Account(Name = 'MidCo',   AnnualRevenue = 1000000),
        new Account(Name = 'HugeCo',  AnnualRevenue = 5000000)
    };

    LargeAccountCriteria criteria = new LargeAccountCriteria();
    criteria.setRecordsToEvaluate(testAccounts);
    List<SObject> result = criteria.run();

    System.assertEquals(2, result.size(),
        'Only BigCo and HugeCo have AnnualRevenue > 1M');
}

Test an Action — drive it the way the coordinator does, with setRecordsToActOn, then read the mutated records:

@IsTest
static void markStrategicAction_setsStatusField() {
    List<SObject> accounts = new List<SObject>{
        new Account(Id = fflib_IDGenerator.generate(Account.SObjectType),
                    Name = 'BigCo', AnnualRevenue = 2000000)
    };

    MarkStrategicAccountAction action = new MarkStrategicAccountAction();
    action.setRecordsToActOn(accounts);   // coordinator does this for you at runtime
    action.runInProcess();

    System.assertEquals('Strategic', ((Account) accounts[0]).Status__c);
}

If an action stages DML against other records, inject a mocked UoW with action.setUnitOfWork(mockUow) and verify its AT4DX register(...) calls.

Test the full coordinator flow with mock bindings — setMockDomainProcessBindings lets you skip the metadata read:

@IsTest
static void coordinator_classifiesLargeAccountsAsStrategic() {
    DomainProcessCoordinator.setMockDomainProcessBindings(
        new List<DomainProcessBinding__mdt>{
            new DomainProcessBinding__mdt(
                Type__c = 'Criteria',
                ClassToInject__c = 'LargeAccountCriteria',
                RelatedDomainBindingSObject__c = 'Account',
                ProcessContext__c = 'TriggerExecution',
                TriggerOperation__c = 'After_Update',
                OrderOfExecution__c = 10.10,
                IsActive__c = true),
            new DomainProcessBinding__mdt(
                Type__c = 'Action',
                ClassToInject__c = 'MarkStrategicAccountAction',
                RelatedDomainBindingSObject__c = 'Account',
                ProcessContext__c = 'TriggerExecution',
                TriggerOperation__c = 'After_Update',
                OrderOfExecution__c = 10.20,
                IsActive__c = true)
        });

    List<Account> accounts = new List<Account>{
        new Account(Name = 'BigCo',   AnnualRevenue = 2000000),
        new Account(Name = 'SmallCo', AnnualRevenue = 100000)
    };

    AccountDomain domain = new AccountDomain(accounts);
    new DomainProcessCoordinator(domain).processDomainLogicInjections(
        DomainProcessConstants.PROCESS_CONTEXT.TriggerExecution,
        System.TriggerOperation.After_Update);

    System.assertEquals('Strategic', accounts[0].Status__c);
    System.assertEquals(null,        accounts[1].Status__c);
}

Running Criteria/Actions Outside a Trigger (DomainMethodExecution)

Sometimes you want the same Criteria/Action machinery from inside a domain method you call yourself — e.g. a service loads accounts, wraps them in a domain, and runs a named recalculation. That is the DomainMethodExecution context, and it is the one case where you invoke the coordinator explicitly, identifying the process by a token (DomainMethodToken__c) instead of a trigger operation.

// In a domain method (not a trigger override):
public void recalculateRevenueTiers(IApplicationSObjectUnitOfWork uow) {
    // 'AccountRevenueTierRecalc' matches DomainProcessBinding__mdt.DomainMethodToken__c
    getDomainProcessCoordinator().processDomainLogicInjections('AccountRevenueTierRecalc', uow);
}

The matching bindings set ProcessContext__c = DomainMethodExecution and DomainMethodToken__c = AccountRevenueTierRecalc (leaving TriggerOperation__c blank). Because you pass a uow here, actions that implement the UoW interface receive it via this.uow and can stage DML.


Cross-Domain Callout

Marketing uses this same pattern for engagement scoring (LowEngagementAccountCriteria + EnqueueNurtureSequenceAction). Service uses it for case escalation (OverdueCaseCriteria + EscalateToManagerAction). Only the class names, the RelatedDomainBindingSObject__c, and the metadata records change — the mechanism is identical. See the Multi-App – Single Org Example.


Next Steps

With the Criteria/Action pattern clear, the next document ties the selector, domain, service, and unit-of-work patterns together in one org shared by Sales, Marketing, and Service.

→ Multi-App – Single Org Example