Domain service shape standard¶
This page sets the rules for the domain services in a ConnectSoft service: the classes in *.DomainModel.Impl that carry out an operation on an aggregate or orchestrate a request. It is written for engineers who add or review those classes. Every public method looks the same, so a reader can trace, measure and diagnose any operation in any service in the same way.
What a domain service is in ConnectSoft templates¶
The ConnectSoft templates have no separate application-service layer. A domain service in *.DomainModel.Impl does the work that DDD texts split between application and domain services:
- it validates the input;
- it loads and changes the aggregate;
- it opens the unit-of-work transaction;
- it publishes the events inside that transaction;
- it records the metrics and writes the logs.
Controllers, gRPC adapters, message handlers and jobs call a domain service and contain no business logic. The DDD background is explained in Domain Services and Application Services.
Rules¶
CS-SVC-001: Give every public domain-service method the house shape¶
Severity: major · Applies to: service, template · Enforced by: manual (target: ENF-035) · Status: active
Why¶
When every operation has the same skeleton, a reviewer can see at a glance whether a failure is logged, counted and rethrown. Operators then find the same three log entries and the same failure counter for every operation in every service. A method that catches and swallows, or that fails without a counter, hides incidents from both logs and dashboards.
Do¶
Write each public method of a domain service in this order:
- Open the flow scope as the first statement, as CS-LOG-003 requires.
- Open a
tryblock that contains, in order:ArgumentNullException.ThrowIfNull(input);- the "started" log entry (CS-LOG-004);
ValidateAndThrowAsyncwith the operation's FluentValidation validator;- the work;
- the "completed" log entry.
- Close with a
catch (Exception ex) when (ex is not OperationCanceledException)block that contains, in order:- the
<Operation>Failedmetric, for exampleAddOrderFailed; - the
LogErrorcall with the exception attached (CS-LOG-004); throw;.
- the
- Give the validator its own test class, as CS-VAL-001 requires.
Don't¶
- Leave out the
catchblock, the failure metric or the rethrow. - Catch a narrower exception type in place of the outer
catch (Exception ex). Narrow catches go inside thetryblock when the operation handles them. - Validate only in the controller. The domain service is called by controllers, gRPC adapters, handlers and jobs alike.
- Return a status or
nullin place of throwing. The API layer maps exceptions to responses.
Example¶
public async Task<IOrder> CreateOrder(CreateOrderInput input, CancellationToken token = default)
{
using (this.logger.BeginScopeWithFlow(nameof(DefaultOrdersProcessor) + "/" + nameof(this.CreateOrder)))
{
try
{
ArgumentNullException.ThrowIfNull(input);
this.logger.Here(log => log.LogInformation(message: "Create Order for {OrderId} started...", input.OrderId));
await this.createOrderInputValidator.ValidateAndThrowAsync(input, token).ConfigureAwait(false);
var stopwatch = Stopwatch.StartNew();
IOrder order = await this.SaveNewOrder(input, token).ConfigureAwait(false);
stopwatch.Stop();
this.meters.AddOrder(stopwatch.Elapsed, tenantId: null, aggregate: nameof(Order));
this.logger.Here(log => log.LogInformation(message: "Create Order for {OrderId} successfully completed...", input.OrderId));
return order;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
this.meters.AddOrderFailed(tenantId: null, aggregate: nameof(Order));
this.logger.Here(log => log.LogError(exception: ex, message: "Failed to create the Order with id : {OrderId}", input?.OrderId));
throw;
}
}
}
How to check¶
- Each public method of a class in
*.DomainModel.Implstarts with the flow scope and has one outertryandcatch (Exception ex). - The
catchblock records a...Failedmetric, logs withexception: exand ends withthrow;. - The
tryblock validates the input before any work. - The outer
catchcarries thewhen (ex is not OperationCanceledException)filter.
CS-SVC-002: Time the success path with a duration histogram¶
Severity: major · Applies to: service, template · Enforced by: manual · Status: active
Why¶
A latency regression shows first in the duration of an operation. When every operation records its duration the same way, one dashboard query covers every service, and the success count, failure count and duration come from the same instruments.
Do¶
- Start a
Stopwatchimmediately before the work (the transaction and the publish) and stop it after the work. - Pass the elapsed time to the operation's success method on the service's metrics class, which records the duration histogram and the success counter.
- Name and shape the instruments as the metrics standard requires.
Don't¶
- Time validation or logging together with the work.
- Record the duration on the failure path. A failure is counted by the
...Failedcounter of CS-SVC-001. - Create a new instrument in the domain service. Instruments live in the metrics class.
How to check¶
Each successful path in a public domain-service method records one call on the metrics class with the elapsed time of the work.
CS-SVC-003: Name domain services Processor, Retriever or UseCase¶
Severity: minor · Applies to: service, template · Enforced by: manual · Status: active
Why¶
The name tells a reader whether a class changes state, reads state or orchestrates other services, before they open it. The templates generate Processor and Retriever pairs, and API gateways and back-ends for front-ends use UseCase classes for orchestration.
Do¶
- Where a service owns an aggregate, put commands in
I<Aggregate>sProcessorand queries inI<Aggregate>sRetriever, both deriving fromIDomainService, withDefault<Aggregate>sProcessorandDefault<Aggregate>sRetrieveras the implementations. - In an API gateway or a back-end for front-end that owns no aggregate, name each orchestration
<Operation>UseCase. - Put the interface in
*.DomainModeland the implementation in*.DomainModel.Impl.
Don't¶
- Put commands and queries for the same aggregate in one service class.
- Use generic suffixes such as
Manager,HelperorServicefor new domain services.
How to check¶
New interfaces in *.DomainModel that change state end in Processor, those that only read end in Retriever, and gateway orchestration classes end in UseCase.
CS-SVC-004: Own the transaction and the publish in the domain service¶
Severity: major · Applies to: service, template · Enforced by: manual · Status: active
Why¶
An event published outside the transaction that wrote the change can announce a change that was rolled back, or be lost after a change that was committed. Keeping the transaction and the publish in one place, the domain service, makes the outbox guarantee in CS-MSG-003 possible.
Do¶
- Open the unit-of-work transaction (
ExecuteTransactionalorExecuteTransactionalAsync) in the domain service. - Publish the events of the operation inside that transaction.
- Keep controllers, gRPC adapters and handlers free of transactions and of publishing.
Don't¶
- Open a transaction in a controller or a repository.
- Publish an event after the transaction has committed.
How to check¶
- In the change, every
PublishEventcall is inside anExecuteTransactionaldelegate in a*.DomainModel.Implclass. - Search controllers, gRPC adapters, handlers and repositories in the change for
ExecuteTransactionalandExecuteTransactionalAsync. They contain none.
CS-SVC-005: Keep each domain-service method under 60 lines¶
Severity: minor · Applies to: service, template · Enforced by: analyzer MA0051 · Status: active
Why¶
The house shape adds about 20 lines of scope, logging, metrics and error handling to each method. Without extraction, the method grows past the length a reviewer can read at once, and MA0051 reports it.
Do¶
- Move the body of the work into a private method, for example
SaveNewOrder. - Move the metric calls into a private method when there are several, for example
RecordCreateOrderMetrics.
Don't¶
- Suppress MA0051 on a domain-service method.
- Drop parts of the house shape to make the method shorter.
How to check¶
- MA0051 reports no method in
*.DomainModel.Implclasses. - Search
*.DomainModel.Implcode and the.editorconfigfiles that apply to it forMA0051suppressions.
CS-SVC-006: Guard every path into a state, reversals included¶
Severity: major · Applies to: service, template · Enforced by: manual · Status: active
Why¶
An invariant such as "one open record per owner" is usually checked by the forward commands that create the state. A cancel, reopen, import or seed path that reaches the same state without the check recreates the conflict that the forward commands refuse.
Do¶
- Put each invariant in one place, such as a policy or the aggregate, and call it from every command that can reach the guarded state.
- List the paths into the state in the invariant's tests, reversals and imports included.
Don't¶
- Reopen, restore or import a record without running the checks that guard its state.
How to check¶
For each invariant, a test performs the forward action, then the reversal, and asserts the refusal.