Multi-App – Single Org Example

This is the end-to-end example. One Salesforce org is shared by three applications — Sales, Marketing, and Service. They share the Account object (Sales and Marketing) and Case (Service), yet there is exactly one selector and one domain per SObject. Each application adds its own fields, queries, and domain behavior through injection — not by subclassing a selector or domain.

It pulls together everything in the docs: the package layers, the four factories, field and method injection, domain process injection, the service triad, and AT4DX Unit of Work.

The Org

flowchart TB
    SALES[sales-app]
    MARKETING[marketing-app]
    SERVICE[service-app]
    SM[sales-marketing-common\nshared Account schema + contracts]
    SS[sales-service-common\nshared Account/Case schema + contracts]
    ORG[org-common\nAccountsSelector · AccountDomain\nCasesSelector · CaseDomain]
    FW[fflib · force-di · AT4DX]

    SALES --> SM
    SALES --> SS
    MARKETING --> SM
    SERVICE --> SS
    SM --> ORG
    SS --> ORG
    ORG --> FW

Marketing has no dependency on sales-service-common; Service has no dependency on sales-marketing-common. These are two purpose-scoped packages in the Business Common layer, not variants of a singular business-common.

What Lives Where

Artifact Package Reason
IAccountsSelector, AccountsSelector, AccountDomain org-common The one Account selector + domain
ICasesSelector, CasesSelector, CaseDomain org-common The one Case selector + domain
Account.EngagementSegment__c sales-marketing-common Shared by Sales and Marketing
Account.CustomerTier__c sales-service-common Shared by Sales and Service
SelectLargeAccountsSelectorMethod, Sales fieldset, Sales Criteria/Actions, *SalesAccountsService* sales-app Sales-owned query, fields, rules, orchestration
SelectByEngagementScoreSelectorMethod, Marketing fieldset, Marketing Criteria/Action marketing-app Marketing-owned query, fields, rules
SelectOverdueCasesSelectorMethod, Service Criteria/Action, *ServiceCaseService* service-app Service-owned query, rules, orchestration

There is no SalesAccountsSelector, MarketingAccountsSelector, SalesAccountDomain, MarketingAccountDomain, ServiceCasesSelector, or ServiceCaseDomain.


Org Common: The Singular Selectors and Domains

All three applications use the same Account classes; Service additionally uses the same Case classes.

public interface IAccountsSelector extends IApplicationSObjectSelector {
    List<Account> selectById(Set<Id> accountIds);
}

public with sharing class AccountsSelector
    extends ApplicationSObjectSelector
    implements IAccountsSelector {

    public static IAccountsSelector newInstance() {
        return (IAccountsSelector)
            Application.Selector.newInstance(Account.SObjectType);
    }

    public Schema.SObjectType getSObjectType() {
        return Account.SObjectType;
    }

    public override List<Schema.SObjectField> getSObjectFieldList() {
        return new List<Schema.SObjectField>{
            Account.Id, Account.Name, Account.Type,
            Account.AnnualRevenue, Account.OwnerId,
            Account.BillingCountry, Account.Status__c
        };
    }

    private List<Schema.SObjectField> getAdditionalSObjectFieldList() {
        return new List<Schema.SObjectField>();
    }

    public List<Account> selectById(Set<Id> accountIds) {
        return (List<Account>) selectSObjectsById(accountIds);
    }
}
public with sharing 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);
        }
    }

    public override void onBeforeUpdate(Map<Id, SObject> existingRecords) {
        for (Account account : (List<Account>) getRecords()) {
            if (String.isBlank(account.BillingCountry)) {
                account.BillingCountry = 'US';
            }
        }
    }
}
ApplicationFactory_SelectorBinding__mdt   Account → AccountsSelector        (Priority 10)
ApplicationFactory_DomainBinding__mdt     Account → AccountDomain.Constructor

CasesSelector and CaseDomain follow the identical shape on Case, registered with their own Account/Case bindings. ApplicationSObjectDomain already invokes DomainProcessCoordinator for trigger operations, so every application injects behavior into these classes through metadata rather than subclassing them.

Common queries call the method directly and do not keep a selector local:

List<Account> accounts = AccountsSelector.newInstance().selectById(accountIds);

Sales

Field Injection

Sales owns a fieldset of the downstream fields its queries must return:

Account.SalesAccountFields: SalesStage__c, ExpectedRevenue__c, EngagementSegment__c, CustomerTier__c

SelectorConfig_FieldSetInclusion__mdt
  BindingSObject__c: Account
  FieldsetName__c:   SalesAccountFields

Every query built by AccountsSelector now includes those fields without Org Common referencing them.

Method Injection

The large-account query belongs to Sales, so it is an injectable method, not a method on a second selector:

// Package: sales-app
public inherited sharing class SelectLargeAccountsSelectorMethod
    extends AbstractSelectorMethodInjectable
    implements ISelectorMethodInjectable {

    public List<SObject> selectQuery() {
        Parameters params = (Parameters) getParameters();
        Decimal minimumRevenue = params.minimumRevenue;

        fflib_QueryFactory queryFactory = newQueryFactory();
        queryFactory.setCondition(Account.AnnualRevenue + ' >= :minimumRevenue');
        queryFactory.addOrdering(Account.AnnualRevenue, fflib_QueryFactory.SortOrder.DESCENDING);
        return Database.query(queryFactory.toSOQL());
    }

    public class Parameters implements ISelectorMethodParameterable {
        public Decimal minimumRevenue;
    }
}
SelectLargeAccountsSelectorMethod.Parameters params =
    new SelectLargeAccountsSelectorMethod.Parameters();
params.minimumRevenue = 1000000;

List<Account> largeAccounts = AccountsSelector.newInstance().selectInjection(
    SelectLargeAccountsSelectorMethod.class, params);

Domain Criteria and Actions

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> matches = new List<SObject>();
        for (Account account : records) {
            if (account.AnnualRevenue != null && account.AnnualRevenue > 1000000) {
                matches.add(account);
            }
        }
        return matches;
    }
}

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> matches = new List<SObject>();
        for (Account account : records) {
            if (account.AnnualRevenue == null || account.AnnualRevenue <= 1000000) {
                matches.add(account);
            }
        }
        return matches;
    }
}

Before-trigger actions mutate records directly; the async action reads the same criteria-filtered set:

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'; }
    }
}

public class NotifyExternalSystemAction extends DomainProcessAbstractAction {
    public override void runInProcess() {
        System.enqueueJob(new StrategicAccountNotifyQueueable((List<Account>) this.records));
    }
}

Sales Domain Process Bindings

Strategic and Standard are mutually exclusive, so they use separate integer sequences:

Sequence 10 — Account / TriggerExecution / Before_Update
  10.10 Criteria LargeAccountCriteria
  10.20 Action   MarkStrategicAccountAction
Sequence 20 — Account / TriggerExecution / Before_Update
  20.10 Criteria SmallAccountCriteria
  20.20 Action   MarkStandardAccountAction
Sequence 30 — Account / TriggerExecution / After_Update
  30.10 Criteria LargeAccountCriteria
  30.20 Action   NotifyExternalSystemAction   (ExecuteAsynchronous__c = true)

Each line is a DomainProcessBinding__mdt record (Type__c, ClassToInject__c, RelatedDomainBindingSObject__c=Account, ProcessContext__c=TriggerExecution, TriggerOperation__c, OrderOfExecution__c, IsActive__c=true). No Sales domain subclass or custom trigger hook is needed.

Sales Service (the triad)

// Interface — in sales-marketing-common if Marketing also compiles against it
public interface ISalesAccountsService {
    void processAccountUpdates(Set<Id> accountIds);
    List<Account> findLargeAccounts(Decimal minimumRevenue);
    Map<Id, String> getAccountStatuses(Set<Id> accountIds);
}

// Static entry point — what callers use
public with sharing class SalesAccountsService {
    private static ISalesAccountsService service() {
        return (ISalesAccountsService)
            Application.Service.newInstance(ISalesAccountsService.class);
    }
    public static void processAccountUpdates(Set<Id> accountIds) {
        service().processAccountUpdates(accountIds);
    }
    public static List<Account> findLargeAccounts(Decimal minimumRevenue) {
        return service().findLargeAccounts(minimumRevenue);
    }
    public static Map<Id, String> getAccountStatuses(Set<Id> accountIds) {
        return service().getAccountStatuses(accountIds);
    }
}

// Implementation — registered in the binding, never referenced by name
public with sharing class SalesAccountsServiceImpl implements ISalesAccountsService {
    public void processAccountUpdates(Set<Id> accountIds) {
        List<Account> accounts = AccountsSelector.newInstance().selectById(accountIds);
        if (accounts.isEmpty()) { return; }

        IApplicationSObjectUnitOfWork uow = Application.UnitOfWork.newInstance();
        uow.register(accounts);
        uow.commitWork();
    }

    public List<Account> findLargeAccounts(Decimal minimumRevenue) {
        SelectLargeAccountsSelectorMethod.Parameters params =
            new SelectLargeAccountsSelectorMethod.Parameters();
        params.minimumRevenue = minimumRevenue;
        return AccountsSelector.newInstance().selectInjection(
            SelectLargeAccountsSelectorMethod.class, params);
    }

    public Map<Id, String> getAccountStatuses(Set<Id> accountIds) {
        Map<Id, String> statuses = new Map<Id, String>();
        for (Account account : AccountsSelector.newInstance().selectById(accountIds)) {
            statuses.put(account.Id, account.Status__c);
        }
        return statuses;
    }
}
ApplicationFactory_ServiceBinding__mdt   ISalesAccountsService → SalesAccountsServiceImpl   (Priority 10)

Callers use SalesAccountsService.processAccountUpdates(ids) and never touch the factory. AT4DX registers records with uow.register(...) (single, list, and parent overloads) — not fflib's registerDirty(...)/registerNew(...).

Marketing

Marketing shares Account with Sales and injects into the same AccountsSelector and AccountDomain.

Method Injection

// Package: marketing-app
public inherited sharing class SelectByEngagementScoreSelectorMethod
    extends AbstractSelectorMethodInjectable
    implements ISelectorMethodInjectable {

    public List<SObject> selectQuery() {
        Parameters params = (Parameters) getParameters();
        Decimal minimumScore = params.minimumScore;
        return Database.query(
            newQueryFactory()
                .setCondition(Account.EngagementScore__c + ' >= :minimumScore')
                .toSOQL());
    }

    public class Parameters implements ISelectorMethodParameterable {
        public Decimal minimumScore;
    }
}
SelectByEngagementScoreSelectorMethod.Parameters params =
    new SelectByEngagementScoreSelectorMethod.Parameters();
params.minimumScore = 70;

List<Account> accounts = AccountsSelector.newInstance().selectInjection(
    SelectByEngagementScoreSelectorMethod.class, params);

Domain Injection

public class LowEngagementAccountCriteria 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> matches = new List<SObject>();
        for (Account account : records) {
            if (account.EngagementScore__c == null || account.EngagementScore__c < 30) {
                matches.add(account);
            }
        }
        return matches;
    }
}

public class EnqueueNurtureSequenceAction extends DomainProcessAbstractAction {
    public override void runInProcess() {
        for (SObject record : this.records) {
            ((Account) record).NurtureStatus__c = 'Needs Outreach';
        }
    }
}
Sequence 40 — Account / TriggerExecution / Before_Update
  40.10 Criteria LowEngagementAccountCriteria
  40.20 Action   EnqueueNurtureSequenceAction

Coordinate sequence ranges across packages. Sequences are grouped by the integer part of OrderOfExecution__c within a given SObject + context + trigger operation. Because Sales already uses sequences 10–20 on Account/Before_Update, Marketing uses 40 — a different integer — so the two packages' criteria do not unintentionally merge into one chained-AND sequence. Agree on per-package OrderOfExecution__c ranges when multiple packages inject into the same domain event.

Note OrderOfExecution__c is a Number(4,2) field — values run 0.00–99.99, so the sequence (integer part) is 0–99 and the in-sequence order uses the two decimal places.

There is no MarketingAccountsSelector and no MarketingAccountDomain.


Service

Service owns Case, injecting into the singular CasesSelector and CaseDomain.

Method Injection

// Package: service-app
public inherited sharing class SelectOverdueCasesSelectorMethod
    extends AbstractSelectorMethodInjectable
    implements ISelectorMethodInjectable {

    public List<SObject> selectQuery() {
        Parameters params = (Parameters) getParameters();
        DateTime cutoff = DateTime.now().addHours(-params.hoursOverdue);
        return Database.query(
            newQueryFactory()
                .setCondition(Case.Status + ' != \'Closed\' AND ' + Case.CreatedDate + ' < :cutoff')
                .toSOQL());
    }

    public class Parameters implements ISelectorMethodParameterable {
        public Integer hoursOverdue;
    }
}

Domain Injection

public class OverdueCaseCriteria implements IDomainProcessCriteria {
    private List<Case> records;
    public IDomainProcessCriteria setRecordsToEvaluate(List<SObject> records) {
        this.records = (List<Case>) records;
        return this;
    }
    public List<SObject> run() {
        DateTime cutoff = DateTime.now().addHours(-24);
        List<SObject> matches = new List<SObject>();
        for (Case caseRecord : records) {
            if (caseRecord.Status != 'Closed' && caseRecord.CreatedDate < cutoff) {
                matches.add(caseRecord);
            }
        }
        return matches;
    }
}

public class EscalateToManagerAction extends DomainProcessAbstractAction {
    public override void runInProcess() {
        for (SObject record : this.records) {
            Case caseRecord = (Case) record;
            caseRecord.EscalationLevel__c = 'Manager';
            caseRecord.Priority = 'High';
        }
    }
}
Sequence 10 — Case / TriggerExecution / Before_Update
  10.10 Criteria OverdueCaseCriteria
  10.20 Action   EscalateToManagerAction

Sequence 10 is free to reuse here because these bindings target Case, a different SObject from Sales' and Marketing's Account sequences. These classes inject into CaseDomain; there is no ServiceCaseDomain.

Cross-App Service Contract

When Service needs a Sales-owned capability, it depends only on the shared contract (in sales-service-common), not the Sales implementation package. Its own service is a triad too:

public interface IServiceCaseService { void handleEscalation(Set<Id> caseIds); }

public with sharing class ServiceCaseService {
    private static IServiceCaseService service() {
        return (IServiceCaseService) Application.Service.newInstance(IServiceCaseService.class);
    }
    public static void handleEscalation(Set<Id> caseIds) {
        service().handleEscalation(caseIds);
    }
}

public with sharing class ServiceCaseServiceImpl implements IServiceCaseService {
    public void handleEscalation(Set<Id> caseIds) {
        List<Case> cases = CasesSelector.newInstance().selectById(caseIds);

        Set<Id> accountIds = new Set<Id>();
        for (Case caseRecord : cases) { accountIds.add(caseRecord.AccountId); }
        accountIds.remove(null);

        if (!accountIds.isEmpty()) {
            // Cross-app call against the shared Sales contract — not its implementation package.
            Map<Id, String> statuses = SalesAccountsService.getAccountStatuses(accountIds);
            for (Case caseRecord : cases) {
                if (statuses.get(caseRecord.AccountId) == 'Strategic') {
                    caseRecord.EscalationLevel__c = 'Executive';
                }
            }
        }

        IApplicationSObjectUnitOfWork uow = Application.UnitOfWork.newInstance();
        uow.register(cases);
        uow.commitWork();
    }
}

Runtime Flow (Sales path)

sequenceDiagram
    participant S as SalesAccountsService (static)
    participant AS as AccountsSelector
    participant IM as SelectLargeAccountsSelectorMethod
    participant U as AT4DX UnitOfWork
    participant T as AccountTrigger
    participant D as AccountDomain
    participant C as DomainProcessCoordinator

    S->>AS: newInstance().selectById(ids)
    AS-->>S: Accounts with injected fields
    S->>U: register(accounts)
    S->>U: commitWork()
    U->>T: Account DML
    T->>D: one Account domain (shared by Sales + Marketing)
    D->>C: automatic trigger-context processing
    C->>C: each sequence: Criteria filter, then Actions execute

    S->>AS: newInstance().selectInjection(method, params)
    AS->>IM: query factory + parameters
    IM-->>S: Sales-specific query results

Comparison

Concern Sales Marketing Service
Primary SObject Account Account Case
Singular selector AccountsSelector AccountsSelector CasesSelector
App-specific query SelectLargeAccountsSelectorMethod SelectByEngagementScoreSelectorMethod SelectOverdueCasesSelectorMethod
Singular domain AccountDomain AccountDomain CaseDomain
Example Criteria LargeAccountCriteria LowEngagementAccountCriteria OverdueCaseCriteria
Example Action MarkStrategicAccountAction EnqueueNurtureSequenceAction EscalateToManagerAction
OrderOfExecution__c range 10–30 (Account) 40 (Account) 10 (Case)

Focused Tests

Test common selector calls by mocking IAccountsSelector — and stub sObjectType(), which setMock requires:

IAccountsSelector selector = (IAccountsSelector) mocks.mock(IAccountsSelector.class);

mocks.startStubbing();
mocks.when(selector.sObjectType()).thenReturn(Account.SObjectType);
mocks.when(selector.selectById(accountIds)).thenReturn(expectedAccounts);
mocks.stopStubbing();

Application.Selector.setMock(Account.SObjectType, selector);

Stub injected calls on the same interface:

mocks.when(selector.selectInjection(
    SelectLargeAccountsSelectorMethod.class, params)).thenReturn(expectedAccounts);

Test Criteria and Actions independently, then drive the coordinator with mock bindings against the org-common AccountDomain (never an app-specific domain):

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

Verify UoW registration with the AT4DX method:

((IApplicationSObjectUnitOfWork) mocks.verify(mockUow, 1)).register(expectedAccounts);

See Testing Patterns for the full mock cheat sheet.

Resulting Boundaries

Next Steps

→ Testing Patterns